Packets: quick start
leet.packets intercepts the client's network packets in both directions: incoming from the server and outgoing to it. A handler sees a packet before the game or the server gets it, and can let it through, block it, or change it.
// On foot: always send the server full armour.
const off = leet.packets.on({ type: 'onFootSync', direction: 'out' }, (packet) => {
if (packet.armour === undefined || packet.armour >= 100) return; // the field is not in this packet, or armour is full
packet.armour = 100;
return packet;
});
// off(); — remove the subscription when you no longer need it. Stop removes every subscription of the script.What a handler returns:
| Result | What happens |
|---|---|
undefined (nothing) | The packet goes on unchanged. Edits you made to the object are not applied. |
false | The packet is blocked. Later handlers do not see it. |
the received packet or an object with fields | The changed fields are written into the packet. |
{ bytes } | The packet is replaced by these bytes. |
leet.packets holds on, raw.on, define, types, send, receive, eventHash, onServerEvent, receiveServerEvent, findEventNames, stats and dispose.
leet.packets.on
on(callback): () => void // every packet, both directions
on(nameOrId, callback): () => void // 'onFootSync' or 138
on({ type?, direction? }, callback): () => voidtypeis a name fromtypes(case-insensitive), an ID 0..255, a name fromdefine, or the'callRemote'selector. Withouttype, every packet arrives.directionis'in'(from the server),'out'(to the server) or'both'(default).- The filter accepts only
typeanddirection. Check anything else with an ordinaryifin the handler. - Returns
off(), which removes exactly this subscription. Calling it again does nothing.
The handler receives a packet:
| Property | What it is |
|---|---|
direction | 'in' or 'out' |
type | the packet name or 'unknown' |
id | packet ID, 0..255 |
bytes | the packet bytes; the first byte is the ID |
bitLength | how many bits of the packet are used (the last byte may be partial) |
channel | mux (210) only: the channel number |
| fields | sync packets and define packets carry them directly: packet.health, packet.position |
own | true for packets sent by send (outgoing) or handed to the client by receive (incoming) |
fields | read-only: the ID139 connection prefix, the incoming 153 game event, an incoming decoded mux channel, the incoming 135 children, the incoming 152 speaker |
inContainer | incoming only: true for a packet that came inside a container (135); on saw the container first |
Rules:
- Handlers run in subscription order. Each one sees the edits of the previous ones.
- A handler is synchronous and runs while the packet waits. Keep it short.
- An error in a handler goes to the script console and cancels only that handler's edit. The packet goes on.
- A Promise changes nothing: the packet is already gone. A rejected Promise goes to the console.
- An edit keeps the ID byte; a field edit also keeps the packet size and the unused bits of the last byte (fields cannot be inserted or removed). Returned
bytesmay have another length (1 to 1492, the ID byte kept): only a container 135, a packet inside one, or one without its own data keeps its size. The next handlers, and the game or the server, get the new length. Fix the length fields inside the body yourself (a mux 210 body, a string length); for a client event, return{ args }fromon('callRemote')instead. A packet grown past about 1400 bytes is split in transit and always sent reliable. - Change either fields or
bytesin one return, not both. If you need both, use two handlers.
| Error (console) | When |
|---|---|
this packet keeps its length (a container 135, a packet inside one, or one without its own data) | returned bytes of another length for a packet that cannot be resized; the packet goes on unchanged |
a resized packet is 1 to 1492 bytes from 0 to 255 and keeps its id byte | the new bytes are empty, too long, change the ID byte or hold a value that is not a byte |
a resized mux packet keeps its 3-byte id and channel header | a mux (210) packet resized to fewer than 3 bytes |
A resized packet ends on a whole byte: its bit length is its byte count times 8, even when a later handler returns it to its first length.
// A chat line: use onSendChat / onReceiveChat (see "Chat events"), not these bytes.
// Cut incoming 201 to its ID and first byte.
leet.packets.on({ type: 201, direction: 'in' }, (p) => ({ bytes: p.bytes.slice(0, 2) }));Reading fields
Sync packet fields sit directly on the packet. A packet carries only what changed, so a field may be missing: test for undefined, not zero.
// On foot (onFootSync): position and health.
leet.packets.on({ type: 'onFootSync', direction: 'in' }, (packet) => {
if (packet.position === undefined) return;
const { x, y, z } = packet.position;
mp.console.logInfo(`player #${packet.playerIndex}: ${x.toFixed(1)}, ${y.toFixed(1)}, ${z.toFixed(1)}, hp ${packet.health ?? '?'}`);
});
// Driver (driverSync): vehicle fields on the packet, the driver's own fields in packet.ped.
leet.packets.on({ type: 'driverSync', direction: 'in' }, (packet) => {
if (packet.vehicleHealth !== undefined)
mp.console.logInfo(`vehicle ${packet.vehicleIndex}: body ${packet.vehicleHealth}`);
if (packet.ped && packet.ped.health !== undefined)
mp.console.logInfo(`driver: hp ${packet.ped.health}`);
});
// Batches (vehicleBatch, pedBatch): records in packet.records.
leet.packets.on({ type: 'pedBatch', direction: 'in' }, (packet) => {
for (const record of packet.records) {
if (record.position) mp.console.logInfo(`ped #${record.pedIndex} at ${record.position.x.toFixed(0)}`);
}
});Carried sync fields
Typed fields exist only on IDs 138, 142, 144, 146 and 147, when the packet is byte-aligned (bitLength is a multiple of 8).
| Fields | Carried by |
|---|---|
position | on-foot, driver, vehicle and ped batch records |
yaw, pitch | on-foot and ped batch records |
weaponHash, ammo, health, healthRaw, healthFlags, weaponDamageEntity, weaponDamageComponent, maxHealth, armour | on-foot, passenger, the driver's ped, ped batch records |
tick | on-foot and driver |
velocity, rotation, angvel, steering | driver and vehicle batch records |
vehicleHealth, bodyHealth, engineHealth, tankHealth | driver and vehicle batch records |
weaponDamageHash, deformation, brokenParts22, brokenParts20, lightsBroken, bumpers | driver and vehicle batch records |
impactCounts, armouredGlass, lastDamagedMaterial | driver and vehicle batch records; arrays of exactly 6, 8 and 8 bytes |
Values:
- Vectors are
{ x, y, z }. - Angles are radians.
yawRawandpitchRaware the same angles as uint16:radians = raw / 10000 - Math.PI. healthis 0..8191 (the low 13 bits).healthRawis the whole 16-bit word. If you change both, the low 13 bits must match.healthFlagsis uint8; the presence bits0x2fcannot change.weaponDamageEntityis a network ID (uint16),weaponDamageComponenta uint8.- A glass byte of 100 means "intact"; an edit cannot turn intact glass into broken glass or back.
- A number must fit its field, otherwise the edit is rejected.
Read-only, cannot change:
- identities:
playerIndex,vehicleIndex,seat,pedIndex,flags,count; taskMask,taskSlots,wheelSuspension,wheelSuspensionMask.
The opaque blocks movementGroup, movement, camera, taskTree, gameState, scriptGameState, heliHealth, task, control, gadget, planeHeliControl and attach decode with the read* functions and write back with the write* functions (below), keeping their byte count.
Also worth knowing:
- The driver's fields are in
packet.ped.vehicleHealthon the packet itself belongs to the vehicle. - A batch has
count(records declared) andrecords(up to 255). A cut packet may hold fewer records thancount. - Incoming
vehicleIndexis a network index, outgoing a game handle. - Outgoing packets have no
playerIndex: the sender is you. - A field the packet does not carry cannot be written: the edit is rejected with a console error.
Camera and aim: readCamera
leet.packets.readCamera(packet.camera) decodes the onFootSync camera block into an object of its fields. It returns undefined when there are no bytes or the block is incomplete. writeCamera writes a changed camera back (see Writing blocks).
| Field | Meaning |
|---|---|
rotation | { x, z } in degrees, like mp.game.cam.getGameplayCamRot(2): x pitch, z heading |
freeCamera, cinematicVehicleCamera, position | a free camera and its world position |
offset, morePrecision | a camera 10 m or more from the player: its offset from the player |
aiming, canMoveWhileAiming | the player is aiming |
aimOffset | where the player aims: from the weapon muzzle to the aim point, up to 150 or 1500 m |
lockedOn, isAimTarget, targetId, targetOffset | a lock-on: the target's network ID and the aim point relative to it |
firstPerson, firstPersonVehicle, firstPersonIdle, stickWithinStrafeAngle, swimming, onSlope | first-person view |
lookAt | the world point the player looks at |
leftTriggerAim | left-trigger aim mode |
Fields the block does not carry (aimOffset when the player is not aiming, for example) are absent.
leet.packets.on({ type: 'onFootSync', direction: 'in' }, (packet) => {
const camera = leet.packets.readCamera(packet.camera);
if (camera && camera.aiming && camera.aimOffset)
mp.console.logInfo(`#${packet.playerIndex} is aiming, heading ${camera.rotation.z.toFixed(0)}`);
});Movement: readMovement and readMovementGroup
leet.packets.readMovement(packet.movement) decodes the movement block and leet.packets.readMovementGroup(packet.movementGroup) the movementGroup block. Like readCamera, they return undefined when there is no block or it is incomplete. A field the game did not send is absent (undefined): 0 for moveBlendRatio.x/y and pitch, 3 for maxMoveBlendRatio; a movementGroup in the default state (on foot, no flags) has motionSet only.
readMovement:
| Field | Meaning |
|---|---|
moveBlendRatio | { x, y }, how fast the player asks to move: 0 still, 1 walk, 2 run, 3 sprint; y forward, x sideways |
stopped | the player has stopped |
pitch | the desired pitch in degrees |
maxMoveBlendRatio | the speed limit, 3 by default |
readMovementGroup:
| Field | Meaning |
|---|---|
motionSet | the walk animation set hash |
moveBlendType, moveBlendState | the movement type and state (1 is on foot) |
weaponSet, strafeSet | hashes of the overridden weapon and strafe animation sets, 0 when none |
crouching, stealthy, strafing, ragdolling | crouched, stealth, strafing, ragdoll |
ragdollAnkleConstraint, ragdollWristConstraint | a ragdoll with tied ankles or wrists |
vehiclePitch | the in-vehicle lean, -1..1 |
leet.packets.on({ type: 'onFootSync', direction: 'in' }, (packet) => {
const movement = leet.packets.readMovement(packet.movement);
if (movement && movement.moveBlendRatio.y > 2.5)
mp.console.logInfo(`#${packet.playerIndex} is sprinting`);
});Ped tasks: readTaskTree
leet.packets.readTaskTree(packet.taskTree) decodes the taskTree block: the script task the player runs and the tasks in the ped's eight task slots. Values are numbers only. It returns undefined when there is no block or it is incomplete.
| Field | Meaning |
|---|---|
scriptCommand | the script task hash; compare with mp.game.joaat('SCRIPT_TASK_PLAY_ANIM'); absent without a script task |
scriptTaskStage | the script task stage |
tasks | [{ slot, type, active, priority, depth, sequenceId }] for the used slots; type is the game's task type number, depth the nesting in the tree |
type numbers follow the current game version and may change with a game update.
const PLAY_ANIM = mp.game.joaat('SCRIPT_TASK_PLAY_ANIM') >>> 0;
leet.packets.on({ type: 'onFootSync', direction: 'in' }, (packet) => {
const tree = leet.packets.readTaskTree(packet.taskTree);
if (tree && tree.scriptCommand === PLAY_ANIM)
mp.console.logInfo(`#${packet.playerIndex} is playing an animation`);
});Vehicle blocks: readVehicleControl, readVehicleGameState, readVehicleTask, readAttach
The vehicle blocks of driverSync and of the vehicle batch records decode the same way, on demand. The functions return undefined when there is no block or it is incomplete.
| Function | What it holds |
|---|---|
readVehicleControl(packet.control) | throttle -1..1, brake 0..1, nitrous, kers, wheels, burnout, topSpeedPercent (-1 when unset), roadNode, hydraulics flags, bringToHalt, gravity, subCar |
readVehicleGameState(packet.gameState) | engineOn, engineStarting, handbrake, radioStation, sirenOn, doors (lockState, open, openRatio, broken, lockStates), windowsDown, lightsOn, fullBeam, stationary, parked, lastDriverId, exclusiveDriverIds, playerLocks, hornHash and other flags |
readVehicleTask(packet.task) | type, the vehicle task number, and dataBits, the length of its data (the data is not decoded) |
readAttach(packet.attach) | attached; when attached, attachedTo, offset, rotation, parentOffset, bones, flags |
readGadget(packet.gadget) | for a trailer, trailerOffset: trailer minus truck in world axes (its length is the hitch distance, 8-11 m); gadgetCount and the gadget data as the string gadgets |
A field the game did not send is absent (undefined); in readVehicleControl that means 0 for brake, throttle and roadNode and -1 for topSpeedPercent. unknownFlag has no documented meaning. Object ids (attachedTo, lastDriverId and so on) are network ids, 16 bits.
heliHealth and planeHeliControl decode by vehicle type; see below.
leet.packets.on({ type: 'driverSync', direction: 'in' }, (packet) => {
const control = leet.packets.readVehicleControl(packet.control);
const state = leet.packets.readVehicleGameState(packet.gameState);
if (control && control.throttle > 0.9 && state && state.sirenOn)
mp.console.logInfo(`#${packet.playerIndex} is speeding with the siren on`);
});Per-type slots and the script state: readVehicleTypeState, readVehicleTypeControl, readVehicleScriptState
The heliHealth slot holds one of six nodes depending on the vehicle type, and planeHeliControl one of two. The block does not say which, so the script passes the type, for example from mp.game.vehicle.isThisModelAHeli(model).
| Call | Types | What it holds |
|---|---|---|
readVehicleTypeState(packet.heliHealth, type) | 'bike', 'boat', 'heli', 'plane', 'submarine', 'train' | bike: onSideStand; boat: lockedToXY, anchorLodDistance, buoyancyForceMultiplier...; heli: rotor, body, tank and engine health; plane: landing gear, section damage, lock-on; submarine: anchored; train: engine and neighbour car ids, track, speed, flags |
readVehicleTypeControl(packet.planeHeliControl, type) | 'heli', 'plane' | yaw, pitch, roll (-1..1), throttle (0..2); heli: engineOff, landing gear, thrusters; plane: reverse thrust, nozzle |
readVehicleScriptState(packet.scriptGameState) | — | the 32 script flags (stolen, disableTowing, canBeVisiblyDamaged...), inAir, parachuting, popType (7 is a script- or server-created vehicle); then slipstreamVehicleId, the parachute, lockedToXY, buoyancyForceMultiplier, restrictedAmmo (6 slots), bombAmmo, countermeasureAmmo, scriptMaxSpeed, flight modes and other script overrides. right after popType, teamLocks (a team mask: team n at bit n + 1), damageScale, weaponDamageScale, blockWeaponSelection, beastVehicle; 2 bits among them are the string overrideFlags, and when one is set, the rest stays in rest |
An unknown type throws. An incomplete block, or a block of another type, reads as undefined.
leet.packets.on({ type: 'vehicleBatch', direction: 'in' }, (packet) => {
for (const record of packet.records) {
const vehicle = mp.vehicles.atRemoteId(record.vehicleIndex);
if (!vehicle || !record.heliHealth || !mp.game.vehicle.isThisModelAHeli(vehicle.model)) continue;
const heli = leet.packets.readVehicleTypeState(record.heliHealth, 'heli');
if (heli && heli.mainRotorHealth < 300) mp.console.logInfo(`heli ${record.vehicleIndex} has a nearly broken rotor`);
}
});Writing blocks: write*
Every read* has a write* twin with the same arguments: writeCamera, writeMovement, writeMovementGroup, writeTaskTree, writeVehicleControl, writeVehicleGameState, writeVehicleTask, writeAttach, writeGadget, writeVehicleScriptState, writeVehicleTypeState(value, type), writeVehicleTypeControl(value, type). It takes the object read* gave (changed or not) and returns the block's bytes. Pass the block's original bytes last: the result is then padded with zeros to their length, and write* throws with both sizes when it does not fit. Put the bytes back on the packet and return the packet:
leet.packets.on({ type: 'onFootSync', direction: 'out' }, (packet) => {
const camera = leet.packets.readCamera(packet.camera);
if (!camera) return;
camera.rotation.z = 90; // the camera faces east
packet.camera = leet.packets.writeCamera(camera, packet.camera);
return packet;
});- An unchanged object writes back the bytes it was read from.
- An optional field is present when it is not
undefined. You may add or drop one while the block still fits its byte count: the packet takes a block only at its size (otherwise "invalid or unsupported sync field edit"). A value that does not fit its field (a wrong number, a wrong type, out of range) makeswrite*throw, naming the field. - Some bits are given as a string of
0and1:tennisinmovementGroup,datainreadVehicleTask,overrideFlagsandrestinreadVehicleScriptState,gadgetsinreadGadget,restin a detachedreadAttach. Leave them as they are. taskMaskcannot be written.taskSlotstake only same-size bytes: they have no decoder.
Connection prefix and raw formats
ID139 has a read-only prefix in packet.fields: nameLength, nameBytes, name, remainingBytes, complete and truncated. name is not the player's name.
An incoming 153 (relayEvent) is one game network event the server relayed to the client. packet.fields holds its read-only decoding:
| Field | What it is |
|---|---|
playerIndex | the player the event came from |
kind, name | the event kind number and its name, e.g. WEAPON_DAMAGE_EVENT (an unknown kind has no name) |
sub, objectMode | the subtype and the "object mode" flag from the header |
argBits | the argument length in bits |
args | the arguments by name, when the kind is known and every field fits |
16 kinds decode: REQUEST_CONTROL_EVENT, GIVE_CONTROL_EVENT, WEAPON_DAMAGE_EVENT (damage type, weapon, damage, hit position and direction, distance and so on), REQUEST_PICKUP_EVENT, GIVE_WEAPON_EVENT, REMOVE_WEAPON_EVENT, REMOVE_ALL_WEAPONS_EVENT, VEHICLE_COMPONENT_CONTROL_EVENT, UPDATE_PROJECTILE_TARGET_EVENT, REMOVE_PROJECTILE_ENTITY_EVENT, BREAK_PROJECTILE_TARGET_LOCK_EVENT, ALTER_WANTED_LEVEL_EVENT, CHANGE_RADIO_STATION_EVENT, RAGDOLL_REQUEST_EVENT, PLAYER_TAUNT_EVENT, REPORT_CASH_SPAWN_EVENT. In object mode and for other kinds there are no args. To change an event, use raw.on: the event fields read with readBits, readSigned and readPackedFloat.
leet.packets.on({ type: 'relayEvent', direction: 'in' }, (packet) => {
const event = packet.fields;
if (event && event.name === 'WEAPON_DAMAGE_EVENT' && event.args)
mp.console.logInfo(`damage from #${event.playerIndex}: weapon ${event.args.weaponHash}`);
});Not every server relays these events to clients: GTA5RP, for example, does not. An outgoing 153 is an event you send (a WEAPON_DAMAGE_EVENT on a hit, for example): its packet.fields has the same shape, with playerIndex holding the target player's remoteId instead of the sender.
Incoming mux (210) on its decoded channels, the container (135) and voice (152) have fields too — below and in the packet types table. Every other packet (16–24 on connect and disconnect, for example) arrives as bytes: read it with raw.on or describe its fields with define.
Mux channels with a decoder
An incoming byte-aligned mux packet (210) on a decoded channel carries its body under packet.fields, read-only like the event of 153: a returned packet still edits by bytes. channel is always set; other channels, outgoing mux and a body cut before its fields have no fields.
leet.packets.on({ type: 'mux', direction: 'in' }, (packet) => {
if (packet.channel === 34 && packet.fields) mp.console.logInfo('entity ' + packet.fields.entityIndex + ' at ' + JSON.stringify(packet.fields.position));
});| Channel | Fields | What it carries |
|---|---|---|
| 18 | kind, entityIndex, modelHash | a model update for a streamed entity |
| 34 | kind, entityIndex, position | a position update for a streamed entity |
| 41 | entityIndex, param, modelHash, flags, position | an entity head plus a vector |
| 124 | entityIndex, param, modelHash, position, value, state | an entity head plus a position, a value and a state |
| 32 | entityIndex, param, modelHash, flags, text | a vehicle plate text (UTF-8) |
| 69 | entityIndex, text | the same plate text without the head |
| 54 | kind, entityIndex, properties, complete | a record stream: { hash, type, value? }, hash is 16 hex digits |
Channel 54 record types are the server event ones: 0x0F int32, 0x11 bool, 0x12 float32, 0x13 text, 0x18 blob, 0x1A no value. A record of another type ends the list, and complete is false unless the last record ends exactly at the packet end.
The mux channels stream entities: positions, models, plates and properties. On GTA5RP, the server's own actions on a player (health, armour, weapon, respawn, freeze, animation, teleport) are server events, not mux channels; see GTA5RP server actions.
Other channels have only channel and bytes.
Chat events: onSendChat and onReceiveChat
leet.packets.onSendChat(callback) gives a script the chat line the client sends, and onReceiveChat(callback) the line the server pushes to the chat, so nobody decodes the mux (210) channel 16 bytes by hand. Channel 16 is RAGE MP's own chat, so both work on any server.
| Channel | Direction | Wire layout | Event |
|---|---|---|---|
| 16 | out | [210, 16, 0][u16 count][UTF-16LE text] (count in UTF-16 code units, not characters) | onSendChat(text, own) |
| 16 | in | [210, 16, 0][u16 count][UTF-8 text] (count in bytes) | onReceiveChat(text, own) |
callback(text, own) returns:
undefined: pass the line on as it is.false: drop it.- a string: use it instead.
''sends an empty line (usefalseto drop). The new line must fit one packet: about 743 UTF-16 units out, 1487 UTF-8 bytes in. A longer one, or a packet that cannot be resized, writes a console error and the original line goes on. - anything else,
nullincluded: an error in the console, the original line goes on.
own is true for a line made by a script's send or receive, so a script can skip its own lines. Several callbacks run in subscription order, each on the text the earlier ones left; one that throws or returns a refused text is reported and skipped. A packet that does not have exactly this shape, and incoming text that is not valid UTF-8, never reaches the callback. Other outgoing channels are not decoded: use on with type: 'mux' and read the bytes.
const off = leet.packets.onSendChat((text, own) => {
if (own) return; // not our own lines
if (text === 'gg') return 'gg, well played'; // send another line
if (text.includes('spoiler')) return false; // do not send
});On GTA5RP neither sees players' messages nor slash commands: players' lines arrive as the chat server event (GTA5RP events by short name), and a slash command (/me ...) does not go out on channel 16. onReceiveChat sees only what the server itself pushes on channel 16.
Container 135
An incoming container (135) carries several packets in one. packet.fields lists them, read-only: packets is [{ id, type, bitLength, bytes }] (type as on a packet: the define name, the built-in name or 'unknown') and complete is false when a child runs past the end and the list is cut. Each child also reaches on by itself right after the container, parsed like any packet of its id and marked inContainer: true, so subscribe to the child's id to read, block or edit it. Blocking the container drops all its children; a returned container edits by bytes.
leet.packets.on({ type: 'container', direction: 'in' }, (packet) => {
mp.console.logInfo('container: ' + packet.fields.packets.map((child) => child.type).join(', '));
});Outgoing RPC selectors
leet.packets.on('callRemote', (call) => {
if (call.name === 'example:report') return false; // do not send
if (call.name === 'example:update') return { args: [100] }; // replace the arguments
if (call.name === 'example:ping') return { args: [...call.args, Date.now()] }; // add an argument
});The 'callRemote', 'callRemoteUnreliable' and 'callRemoteProc' selectors intercept outgoing mp.events.callRemote, callRemoteUnreliable and callRemoteProc. It does not matter who made the call: your script, another script, or the server's own client scripts. The handler gets a call object.
| Property | Type | Meaning |
|---|---|---|
call.direction | string | Always 'out'. |
call.wireName | string | The event name exactly as it is sent to the server. Some servers encode event names on the wire, so this may not be readable. Read-only. |
call.name | string | The readable event name when the client knows it, otherwise the same as call.wireName. Never null. |
call.args | Array | A copy of the call's arguments after the event name. You can change it; the real call is untouched until you return an edit. |
How call.name relates to call.wireName:
| Situation | call.name |
|---|---|
| The name is not encoded on the wire | same as call.wireName |
| The name is encoded and the client knows the readable name | the readable name |
| The name is encoded and the readable name is unknown | same as call.wireName |
-
For display and logs, use
call.name: it is always a string. -
To match exactly what the server receives, compare against
call.wireName. -
On GTA5RP
call.namemay be a best guess of the readable name; the event logger marks such names with~, whilecall.namecarries no marker. -
argsis a copy of the arguments. You can change it: the real call is untouched until you return an edit. -
Return
{ name },{ args },{ name, args }or thecallitself to change the call. The name cannot be empty. -
argsmay have a different length: add or drop arguments, as inreturn { args: [...call.args, 'extra'] }orreturn { args: [] }. The server receives exactly the new list. AcallRemoteProcwith a changed count still returns its Promise to the caller.argsthat is not an array is refused with an error in the console. Only that handler's edit is dropped: edits accepted before it, a changed count included, still go out.- The packet stores the count in 16 bits, so a changed list can never hold more than 65535 arguments. That is the field's ceiling, not a promise that the packet or the server takes that many.
- In the rare case the client cannot build the call with the new count, the original call goes out unedited.
- A replay from the event logger goes through the handlers again: a handler that appends an argument appends it again.
-
An edit of
{ name }sets the wire name.return { name: 'bank:transfer' }sends exactlybank:transferto the server (unless that is the call's readable name: then nothing changes and the wire stays). On GTA5RP, if the call must stay encoded, passleet.events.crypt('bank:transfer'). If a subscriber renames the call, the later subscribers seename === wireName: the old readable name no longer describes the new wire. An argument-only edit keeps the name, even when it returns thecallitself, a copy or a spread of it (return { ...call, args }): a name that is still the readable one is not a rename. -
wireNameanddirectionare read-only metadata: an edit carrying a differentwireNameis refused just like a changeddirection. -
The handler runs synchronously, before the call is sent. Remote calls made inside the handler are sent normally but are not shown to handlers again. An exception in a handler affects neither the other handlers nor the call.
-
Arguments holding native objects, functions or getters cannot be copied: reading
argswrites an error to the console. Such a call can still be blocked by name or renamed. -
A blocked
callRemoteProcnever reaches the server, so its Promise never settles. Do not block a procedure whose result your own code awaits. -
Stop, unload and reconnect remove the subscription by themselves;
off()removes it earlier. At most 32 subscriptions per selector exist in the whole client at once. -
direction: 'in'is not supported for these selectors. Subscriptions withouttypeor by numeric ID get packets, not calls.
Block one procedure inside a shared RPC transport
Some servers send every RPC through a single wire (__rpc:process), so the interesting name is inside the JSON payload and not in call.wireName.
leet.packets.on('callRemote', (call) => {
if (call.wireName !== '__rpc:process' || !call.args.length) return;
let data;
try { data = JSON.parse(call.args[0]); } catch (e) { return; }
if (data?.name !== '__rpc:triggerEvent' || !Array.isArray(data.args) || data.args[0] !== 'server_player_mainMenuOpen') return;
return false; // the server never sees this trigger
});Blocking a __rpc:triggerEvent is safe: it is sent with noRet and waits for no answer. Blocking any other __rpc:process call (a callServer without noRet) leaves its promise pending forever, or until the timeout set for it.
Replace one value inside a shared RPC transport
leet.packets.on('callRemote', (call) => {
if (call.wireName !== '__rpc:process' || !call.args.length) return;
let data;
try { data = JSON.parse(call.args[0]); } catch (e) { return; }
if (data?.name !== '__rpc:triggerEvent' || !Array.isArray(data.args) || data.args[0] !== 'server_player_mainMenuOpen') return;
data.args[1] = 'shop';
return { args: [JSON.stringify(data)] }; // one value: the call has one argument
});The same filter as the recipe above, but the call goes out with a different argument. Leave id, env and noRet untouched: for a callServer the response finds its promise by id.
Count remote calls and print a summary every 10 seconds
const counts = new Map();
leet.packets.on('callRemote', (call) => {
counts.set(call.name, (counts.get(call.name) || 0) + 1);
});
const timer = setInterval(() => {
if (counts.size === 0) return;
const top = [...counts.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, 5)
.map(([name, n]) => `${name}: ${n}`)
.join(', ');
mp.console.logInfo(`[remote top 5 / 10s] ${top}`);
counts.clear();
}, 10000);
leet.events.onUnload(() => clearInterval(timer));The handler only counts and the timer prints. Stop removes the subscription itself; onUnload removes the timer.
Measure the unreliable call rate per event
const perSecond = new Map();
leet.packets.on('callRemoteUnreliable', (call) => {
perSecond.set(call.name, (perSecond.get(call.name) || 0) + 1);
});
const timer = setInterval(() => {
for (const [name, n] of perSecond) {
if (n >= 20) mp.console.logWarning(`[unreliable] ${name}: ${n}/s`);
}
perSecond.clear();
}, 1000);
leet.events.onUnload(() => clearInterval(timer));Unreliable calls arrive often, so the handler does one Map write and nothing else. Once a second the timer reports events with 20 or more calls per second.
Warn about an observed remote call
leet.packets.on('callRemote', (call) => {
if (call.name === 'bank:transfer') {
leet.ui.notify(`Transfer sent: ${JSON.stringify(call.args)}`, 'warning');
}
});The notification appears only for the call you want. call.name is always a string: on a server without obfuscation it equals the wire name.
Incoming server events
const inventory = leet.packets.eventHash('client_inventory_open');
leet.packets.on('serverEvent', (event) => {
if (event.rpc) mp.console.logInfo('rpc ' + JSON.stringify(event.rpc).slice(0, 200)); // rage-rpc servers
if (event.hash === inventory) return false; // block the event before the client handles it
});The 'serverEvent' selector gets every event the server sends to the client (player.call on the server), on any RAGE MP server. The handler gets { direction: 'in', hash, name, args, bytes }.
hashis the event name's hash as 16 hex digits: the server sends only the hash.eventHash(name)computes it, and after thatnameis filled for events with that hash.'__rpc:process'and'__rpc:processPartial'are known from the start.argsholds the decoded arguments: whole numbers, floats, booleans, strings, and{ entity, id }for an entity (entityis the type tag,idthe remote ID). An argument of an unsupported type stops the read:argskeeps what came before it andpartialistrue.rpcis set for rage-rpc's'__rpc:process': its JSON string parsed,{ req, id, name, args, env, noRet }. A server event sent through rage-rpc isrpc.name === '__rpc:triggerEvent'withrpc.args = [eventName, eventArgs].- Return
falseto block the event, or a new args array to change it, at any length. For rage-rpc, changeevent.rpcin place and return[JSON.stringify(event.rpc)]. The new bytes replace the packet: the next handlers see the edit and the client handles it in the same frame. A number is written as int32 when it is whole, else float32; an argument that arrived as float32 stays float32. An argument is an int, a float, a bool, a string or{ entity, id }; apartialevent, and one with bytes after its arguments (a server event with bytes after its arguments cannot be edited), cannot be edited. An event inside a container 135 keeps its length: an edit of another length writesthis packet keeps its lengthto the console and the original passes. An event made byreceiveServerEventarrives withown: true. direction: 'out'is not supported.- Big rage-rpc messages (over 32000 characters, such as the GTA5RP inventory) arrive in parts,
'__rpc:processPartial'events[id, index, total, chunk]. leet joins them like rage-rpc's client does: subscribers get the parts' content as one'__rpc:process'event on the packet of the last part, withrpcparsed,joinedset to the number of parts andbytesof that last part. The earlier parts are not given to subscribers (read them withon('mux')if you need the raw parts). The parts always reach the game; a message that does not complete leaves nothing for subscribers. Blocking a joined message (false) blocks only its last part: the client never completes the message, but its own rage-rpc keeps the earlier parts in memory for good (up to about 2 MB per message), so a block is a leak, not a clean drop. Editing a joined message is refused (a joined rage-rpc message cannot be editedin the console, the original passes; returning it unchanged is not an edit): the earlier parts are already with the game and cannot be taken back. Waiting parts are bounded: up to 64 parts per message of up to 32000 characters each (rage-rpc's own cut; a longer part stays a plain event), 8 messages at once, a message not finished in 30 s is dropped; reconnecting and Stop clear them. - Every
serverEventandonServerEventsubscriber gets its own copy of the event, in subscription order. When a subscriber edits the packet it is decoded again for the next ones, so they see the edit. A subscriber that throws, or whose edit is refused, is reported and skipped. A block stops the later subscribers. All of them run at the position of the first server-event subscription: anon('mux')handler subscribed between two server-event subscribers runs after both.
onServerEvent(name, callback) subscribes to one event: callback(args, event), return false to block. A RAGE event matches by its name's hash and passes its args; a rage-rpc event (__rpc:triggerEvent naming it) passes its own argument. Return a new value of what the callback got (the args array, or the rage-rpc argument) to change the event. When the name is not known, pass the 16-hex-digit hash you saw on serverEvent instead; it also matches a rage-rpc event whose name has that hash.
GTA5RP events by short name
On GTA5RP, onServerEvent and receiveServerEvent also take the short names below, like onServerMessage in SAMP.Lua. A short name means its GTA5RP event only while you are on GTA5RP (checked on each event, so a subscription made before the join works too); on another server it is an ordinary event name with whatever arguments that server sends. receiveServerEvent('inventory', …) is refused (a console error and null): the client takes that event only through rage-rpc, so build its '__rpc:process' envelope as in the recipe Change a server event, or send the client a fake one. The arguments are the ones the GTA5RP client's own handler takes.
| Name | Callback gets | What it is |
|---|---|---|
chat | [senderId, kind, text] | A chat line. senderId is the remote ID of the player who wrote it, you included. text is the bare text, without the name. kind: 0 say, 1 shout, 2 whisper, 3 OOC, 4 /me, 5 /do, 6 /try, 7 /todo (text is speech*action). |
announcement | [name, name, text, contact, extra] | An ad in the news feed: five strings. contact is a phone written as |ph|1234567|ph|; extra is usually empty. |
notify | [kind, text] | An on-screen notification. kind is a string, for example 'error' or 'info'. |
money | [cash, notify] | Your cash changed: the new total, and whether the client shows the + N$ / - N$ notice. |
inventory | data (an object) | The inventory opened. This is a rage-rpc event: the callback gets one object ({ type: 'playerInventory', maxWeight, weight, ... }), not an array; return a changed object to edit it. |
const off = leet.packets.onServerEvent('chat', ([sender, kind, text]) => {
if (kind === 4) mp.console.logInfo('/me from ' + sender + ': ' + text);
if (/casino/i.test(text)) return false; // hide this line
});
leet.events.onUnload(off);
leet.packets.receiveServerEvent('notify', ['info', 'only you see this']);findEventNames(hashes) looks up readable names for hashes, up to 64 per call; a name is not found for every hash. It returns { hash: name } for the ones found, and from then on name is filled for events with those hashes. The search takes up to 1.5 s, and the game waits for it: call it once at start, not per event.
const names = leet.packets.findEventNames(['c7bc8bf21f4ea34f']);
mp.console.logInfo('chat event: ' + (names.c7bc8bf21f4ea34f || 'not found'));To change a rage-rpc event, return its new argument; details and faking an event are in the recipe Change a server event, or send the client a fake one.
const off = leet.packets.onServerEvent('inventory', (data) => {
if (data && data.type === 'playerInventory') return { ...data, maxWeight: 777 }; // any change, any length
});
leet.events.onUnload(off);GTA5RP server actions
On GTA5RP, the server's own actions on a player are server events, not the built-in mux channels:
c:character:weapons:setwith[hash, ammo, ...]gives a weapon;[0,0,0]removes it. The hash may arrive as a string.c:character:weapons:setAmmowith[30, -1]changes ammo.c:player:blodyWoundsandc:characterDeath:setDataare death and respawn.c:player:afk:statusandc:sync:anim:reSyncare state and animation.37d5ee251735e848is an event known only by its hash; subscribe to the hash (busted,idle_b, 1).
The mux channels 210 carry the streaming of other entities (models, positions, plates, properties), not the local player's own actions. Use onServerEvent for the actions above; on('mux') only shows the stream.
leet.packets.raw.on
leet.packets.raw.on(210, (stream) => {
stream.seek(8); // skip the ID byte
const channel = stream.readUint16();
mp.console.logInfo(`mux channel ${channel}, ${stream.bitLength - stream.tell()} bits left`);
});raw.on(id, callback) gives a bit stream over the packet bytes, without parsing fields. The ID is a number 0..255; both directions arrive. The cursor starts at bit 0, the ID byte. Handler order is shared with on.
Stream properties: id, direction, bitLength, bytes.
| Method | Reads and writes |
|---|---|
readBits(n) / writeBits(value, n) | an unsigned number of n bits (1..32), most significant bit first |
readSigned(n) / writeSigned(value, n) | a sign bit and a magnitude of n - 1 bits (2..32), as in game network events |
readBool() / writeBool(value) | one bit |
readUint8(), readUint16(), readUint32() and write…(value) | unsigned 1, 2, 4 bytes, little-endian |
readInt8(), readInt16(), readInt32() and write…(value) | signed 1, 2, 4 bytes, little-endian |
readFloat32() / writeFloat32(value) | a 4-byte float, little-endian |
readVector2() / writeVector2({ x, y }) | two floats |
readVector3() / writeVector3({ x, y, z }) | three floats |
readBytes(n) / writeBytes(array) | n bytes |
readString(prefixBits = 8) / writeString(text, prefixBits = 8) | a length (8, 16 or 32 bits), then UTF-8 bytes |
readFixedString(size) / writeFixedString(text, size) | a string in exactly size bytes: UTF-8 up to the first zero byte, zero-padded on write |
readPackedFloat(bits, max) / writePackedFloat(value, bits, max) | a packed float: sign and magnitude in bits bits, scaled from -max to max |
readUnsignedPackedFloat(bits, max) / writeUnsignedPackedFloat(value, bits, max) | the same without a sign: scaled from 0 to max |
seek(bit) / tell() | move to bit 0..bitLength / get the current bit |
Multi-byte numbers are little-endian. You can read and write from any bit, not only at a byte boundary. Game event fields (relay 153) are bit fields: use readBits and readSigned for them.
- A bad read or write (past
bitLength, a number that does not fit, a string longer than its prefix) throws and changes neither the bytes nor the cursor. - To apply what you wrote, return the same stream.
undefineddiscards the writes,falseblocks the packet. - Written bytes keep the packet size, the ID byte and the unused bits of the last byte.
leet.packets.define
define(id, name, fields): voiddefine describes the fields of a packet leet does not parse. The packet then arrives in on with the fields directly on it and your name in type, and you can subscribe by that name.
leet.packets.define(210, 'muxFrame', [
['chan', 'uint16'],
['body', 'bytes'],
]);
leet.packets.on({ type: 'muxFrame', direction: 'in' }, (packet) => {
if (packet.chan === undefined) return; // the packet did not fit the layout
mp.console.logInfo(`channel ${packet.chan}, ${packet.body.length} bytes`);
});idis 0..255, except the sync packets (138, 142, 144, 146, 147) and 139: they already have fields.nameis a JavaScript identifier. It cannot take a name fromtypes,callRemote,callRemoteUnreliable,callRemoteProcor anotherdefine's name. Defining the same ID again replaces the layout.fieldsis a list of[name, type]pairs, in the order they follow the ID byte. Field names cannot bedirection,type,id,bytes,bitLength,channelorfields.
| Type | Value |
|---|---|
uint8, uint16, uint32, int8, int16, int32 | an integer, little-endian |
float32 | a number |
bool | true / false, one bit |
bool8, bool32 | true / false in 1 or 4 bytes (non-zero is true) |
vector2, vector3 | { x, y }, { x, y, z } |
string8, string16, string32 | a string with an 8, 16 or 32-bit length |
bits:N | an unsigned number of N bits (1..32) |
signed:N | sign and magnitude, N bits (2..32) |
bytes:N | an array of N bytes |
fixedString:N | a string in exactly N bytes |
packedFloat:B:M, unsignedPackedFloat:B:M | a packed float of B bits, scaled up to M (for example packedFloat:16:90) |
bytes | all remaining bytes; last field only |
A type can also be composite:
| Type | Value |
|---|---|
[[name, type], ...] | a nested object with these fields |
{ array: type, count: N } | an array of N items |
{ array: type, count: 'field' } | an array whose length is the value of an earlier field at the same level |
{ read(stream, scope), write(stream, value, scope) } | your own functions: stream is a stream, scope the fields already read at the same level |
leet.packets.define(152, 'squad', [
['count', 'uint8'],
['members', { array: [['id', 'uint16'], ['hp', 'uint8']], count: 'count' }],
['origin', [['x', 'int16'], ['y', 'int16']]],
]);
leet.packets.on('squad', (packet) => {
packet.members[0].hp = 100; // edit in place
return packet;
});Reading and writing:
- If the packet does not fit the layout (it is shorter than needed), no fields appear and the packet goes on as usual.
- Return the packet to write the changed fields. Unchanged fields keep their bytes.
- A changed field must keep its size: a string of the same byte length, an array of the same length. Nested objects and arrays can be edited in place: a changed field is written whole.
- An unknown key in the returned object, or a value that does not fit its field, rejects the whole edit with a console error.
- A layout applies only in the script that defined it.
leet.packets.send
send(id: number, writer: (stream: PacketBitStream) => void, options?: SendOptions): number | null // raw form
send(name: string, fields: object): true | number // typed formSends a packet to the server. Two forms:
Raw form send(id, writer) — id 0..255 and a writer function. The writer fills a zeroed buffer through the same bit stream raw.on reads with: writeUint8, writeBits and the rest. Returns the number of bytes the writer filled. The packet goes out with the writer's bytes and its exact bit length.
Typed form send(name, fields) — a name from types or define, and a fields object. The fields are written over the template — the client's last outgoing packet of that id: send('onFootSync', { ...last, position: { x: me.x + 0.5, y: me.y, z: me.z } }) sends a copy of the client's last packet with the position shifted. Returns true (sync packets) or the byte count (layouts from define). Fields the object does not carry and the tail stay as the template has them, the packet size does not change.
Delivery options (raw form only) — { reliability, priority, channel }, each optional. Without options the packet goes out with the delivery of the client's own last packet of that id, so an id the client never sent is refused. With options, a word you leave out keeps that value (or the client's usual sync delivery, unreliableSequenced, system, channel 0, if the id was never sent), and the id does not have to have been sent by the client: the packet goes to the server the client's latest packet went to.
| Option | Values | Meaning |
|---|---|---|
reliability | 'unreliable' | may be lost or reordered, no resend |
'unreliableSequenced' | may be lost; an older packet that arrives late is dropped (what the client's sync packets use) | |
'reliable' | resent until acknowledged; no order | |
'reliableOrdered' | resent, and delivered in send order within the channel | |
'reliableSequenced' | resent; only the newest of the channel is kept | |
priority | 'system', 'high', 'medium', 'low' | send queue priority, system first |
channel | integer 0..31 | ordering channel; ordered and sequenced packets only keep order inside one channel |
A packet over about 1400 bytes is split in transit, and an unreliable reliability is then raised to its reliable form (unreliable → reliable, unreliableSequenced → reliableSequenced). The reliabilities with an acknowledgement receipt are not offered. The options exist in the raw form only; at least one is required. Packets of one ordering channel wait for each other: a reliableOrdered packet on a channel the server never reads can stall that channel, so use a channel the client already uses or 0.
Errors throw an exception (all prefixed with leet.packets: ):
| Error | When |
|---|---|
send options must be an object { reliability, priority, channel } | options is not an object |
send option ... | an unknown key, or a value not in the tables above (reliability, priority, channel 0..31), an empty object, or options on the typed form |
no client packet observed yet, so the server address is unknown | options given before the client sent any packet |
send needs a numeric packet id from 0 to 255 | id is not a number 0..255 (raw form) |
send needs a writer function | the writer is not a function (raw form) |
send needs a synchronous writer | the writer returned a promise: what it would write after an await would be lost, so nothing is sent (raw form) |
the writer wrote no bytes | the writer wrote nothing (raw form) |
send needs an id from 0 to 255 and 1 to 1492 bytes from 0 to 255 | the packet exceeds 1492 bytes (raw form) |
unknown packet type "..." | the name is not in types/define (typed form) |
send(name, fields) needs a sync packet or a define() layout; use send(id, writer) for "..." | the packet has no parsed fields to write (typed form): use the raw form |
send needs a fields object for a named packet | fields is not an object (typed form) |
no client packet of id N observed yet, so its send template is unknown | the client has not sent a packet of that id yet — no template (typed form) |
no client packet of id N observed yet, so its send defaults are unknown | same for the raw form |
send refused inside the outgoing delivery | sending from inside the on handler of the same packet |
not connected | no server connection |
the template bytes do not fit the "..." layout | the template bytes do not fit the define layout (typed form) |
the fields do not fit the "..." packet layout | a field does not fit the layout (typed form) |
the fields do not match the current template of "..." | the fields do not match the current template (typed form) |
A writer error cancels the send and reaches the console; in that case send returns null.
The sent packet passes through the outgoing on with the mark own: true, so the handler can tell it from the client's own traffic and not loop.
// Send a copy of the client's last packet with the position shifted by 0.5 m.
let last = null;
leet.packets.on({ type: 'onFootSync', direction: 'out' }, (packet) => {
if (packet.position && !packet.own) last = packet; // a client packet, not our own
});
const timer = setInterval(() => {
if (!last) return;
const me = mp.players.local.position;
try {
leet.packets.send('onFootSync', { ...last, position: { x: me.x + 0.5, y: me.y, z: me.z } });
} catch (error) {
// the packet shape changed since `last`: wait for the next one
}
}, 1000);
leet.events.onUnload(() => clearInterval(timer));leet.packets.receive
receive(id: number, writer: (stream: PacketBitStream) => void): number | null // raw form
receive(name: string, fields: object): true | number // typed formHands the client a packet as if the server sent it. Two forms:
Raw form receive(id, writer) — id 0..255 and a writer function: the writer fills a zeroed buffer through the same bit stream raw.on reads with, starting with the id byte. Returns the number of bytes handed over (a partial last byte counts whole: a received packet has no bit length of its own).
Typed form receive(name, fields) — a name from types or define, and a fields object. The fields are written over the template — the server's last packet of that id; fields the object does not carry and the packet's tail stay as the template has them. Returns true (sync packets) or the byte count (layouts from define).
- The template is kept from the first typed
receiveof that id until the script stops. So the first call fails ("no template yet"), and from the next server packet of that id on it works: retry a little later (example below). - Only the server's packets become a template, never your own copies.
- Templates are kept for at most 16 ids at once; a typed
receiveof a 17th id keeps failing. - Take the fields from the very last server packet of that id, unfiltered: that packet is the template (from any player). A sync packet's shape changes from packet to packet, and the fields of an older packet, even one packet older, often do not match the template (
the fields do not match the current template).
How and when the packet reaches the client:
- On the next frame, not inside the call. The packet first passes through the incoming
onhandlers with the markown: true(they can block or edit it), then the game handles it like any server packet. - Up to 16 packets on their way at once, so a script can hand over several in one frame; each is marked
ownexactly once. A 17th call fails until earlier ones have arrived. - Right after the first incoming
onof an id, areceiveof that id may be held for a moment (the call still returns at once) so the handlers do not miss it. If they still cannot see it after about 2 s, the packet is handed over anyway, unseen by the handlers. - What the game does with it is the game's business: a sync packet (138, 142, 144, 146, 147) only updates an entity the client already has, a mux packet (210) only reaches a channel the server registered. Nothing goes to the server.
Errors throw an exception (all prefixed with leet.packets: ):
| Error | When |
|---|---|
receive needs a numeric packet id from 0 to 255 | id is not a number 0..255 |
receive needs a writer function | the writer is not a function |
receive needs a synchronous writer | the writer returned a promise |
the writer wrote no bytes | the writer wrote nothing |
the first byte the writer writes must be the packet id N | the first byte is not id |
receive needs 1 to 1492 bytes from 0 to 255 (a mux packet at least 3) | the packet is too long, or a mux packet has no channel |
receive refused: 16 received packets are already on their way | 16 earlier receive calls have not arrived yet |
not connected | no server connection |
unknown packet type "..." | the name is not in types/define (typed form) |
receive(name, fields) needs a sync packet or a define() layout; use receive(id, writer) for "..." | the packet has no parsed fields to write, 'mux' for example (typed form): use the raw form |
receive needs a fields object for a named packet | fields is not an object (typed form) |
no server packet of id N received yet, so its receive template is unknown | no server packet of that id since the first typed receive of it — no template (typed form) |
the template bytes do not fit the "..." layout | the template bytes do not fit the define layout (typed form) |
the fields do not fit the "..." packet layout | a field does not fit the layout (typed form) |
the fields do not match the current template of "..." | the fields do not match the current template (typed form) |
A writer error cancels the call and reaches the console; in that case receive returns null.
// Raw form: hand the client one more copy of the next mux packet of channel 35 the server sends.
const off = leet.packets.on({ type: 'mux', direction: 'in' }, (packet) => {
if (packet.own || packet.channel !== 35) return; // a server packet, not our own copy
off();
const bytes = packet.bytes;
setTimeout(() => leet.packets.receive(bytes[0], (stream) => stream.writeBytes(bytes)), 0);
});
leet.events.onUnload(off);// Typed form: show a player 20 m higher than the server sent them (until their next packet).
let last;
const off = leet.packets.on({ type: 'onFootSync', direction: 'in' }, (packet) => {
if (!packet.own) last = packet; // the very last server packet, the base for the fields
});
const timer = setInterval(() => {
if (!last || !last.position) return; // the last packet has no position: wait for the next
const { x, y, z } = last.position;
try {
leet.packets.receive('onFootSync', { ...last, position: { x, y, z: z + 20 } });
clearInterval(timer); // handed over once
} catch (error) {
mp.console.logInfo(error.message); // the first call: no template yet, try again
}
}, 500);
leet.events.onUnload(() => { off(); clearInterval(timer); });leet.packets.stats and dispose
stats() returns { incoming: { seen, blocked, rewritten, missed }, outgoing: { seen, blocked, rewritten, missed } } — client-wide counters, not per script:
seen— packets the handlers got;blocked— blocked;rewritten— changed;missed— packets that could not be shown to the handlers.
dispose() removes every packet subscription of the script, including raw.on and the RPC selectors. Stop, unload and reconnect do the same.
Packet types
types is the list of known names. A name does not mean the packet has parsed fields: see the "Body" column.
| ID | Name | Body |
|---|---|---|
| 16 | connectionAccepted | bytes |
| 17 | connectionFailed | bytes |
| 20 | serverFull | bytes |
| 21 | disconnect | bytes |
| 22 | connectionLost | bytes |
| 23 | connectionBanned | bytes |
| 24 | invalidPassword | bytes |
| 135 | container | incoming: its children in packet.fields |
| 138 | onFootSync | sync fields |
| 139 | connectionEstablished | prefix in packet.fields |
| 142 | passengerSync | sync fields |
| 144 | driverSync | sync fields |
| 146 | vehicleBatch | sync fields |
| 147 | pedBatch | sync fields |
| 152 | voice | incoming: the speaker's playerIndex in packet.fields; the codec frame after it stays bytes |
| 153 | relayEvent | a game network event in packet.fields (playerIndex: the sender when incoming, the target when outgoing) |
| 210 | mux | bytes; channel number in channel; incoming decoded channels: packet.fields |
Recipes: packets
Find the nearest player on foot
const seen = new Map(); // playerIndex -> position
leet.packets.on({ type: 'onFootSync', direction: 'in' }, (packet) => {
if (packet.position) seen.set(packet.playerIndex, packet.position);
});
const timer = setInterval(() => {
const me = mp.players.local.position;
let best;
for (const [index, p] of seen) {
const distance = Math.hypot(p.x - me.x, p.y - me.y, p.z - me.z);
if (!best || distance < best.distance) best = { index, distance };
}
if (best) mp.console.logInfo(`nearest #${best.index}: ${best.distance.toFixed(1)} m`);
}, 1000);
leet.events.onUnload(() => clearInterval(timer));Keep one event from reaching the server
leet.packets.on('callRemote', (call) => {
if (call.name === 'example:afkCheck') return false;
});Change a server event, or send the client a fake one
A handler returns the changed arguments (any length, like onServerMessage in SAMP.Lua); receiveServerEvent(name, args) gives the client an event the server never sent (like RakHook's emul_rpc). The edit replaces the server's packet before the client handles it; the fake event goes through receive and is handled on the next frame. Nothing reaches the server. On GTA5RP the chat line is 'chat' (the server's 'c:chat:m') with [senderId, kind, text]:
const off = leet.packets.onServerEvent('chat', ([sender, kind, text]) => {
return [sender, kind, text + ' [edited]']; // the client shows the edited line
});
leet.events.onUnload(off);
leet.packets.receiveServerEvent('chat', [-1, 0, 'only you see this line']);namemay be the 16-hex-digit hash when the name is not known, or a GTA5RP short name.argsare ints, floats, bools, strings or{ entity, id }.receiveServerEventhasreceive's limits and refusals. A bad argument, like a throwingreceivewriter, writes an error to the console and returnsnull.- Handlers after the editing one see the edited event; the fake event reaches the handlers with
own: true. A handler that answers event X withreceiveServerEvent(X, …)gets its own fake back on the next frame: skipevent.ownevents, or it runs every frame. - An event inside a container 135 keeps its length (
this packet keeps its length, see above). - For a rage-rpc event build the envelope yourself (
receiveServerEvent('__rpc:process', [JSON.stringify({ req: 1, id, name: '__rpc:triggerEvent', env: 'server', args: [eventName, data], noRet: 1 })])) and keepnoRet: 1: without it the client answers the server about a call the server never made.
Check that an edit works without sending it
The second handler sees the first one's edit and blocks the packet, so the changed value goes nowhere.
leet.packets.on({ type: 'onFootSync', direction: 'out' }, (packet) => {
if (packet.armour === undefined) return;
packet.armour = 50;
return packet;
});
leet.packets.on({ type: 'onFootSync', direction: 'out' }, (packet) => {
if (packet.armour === 50) mp.console.logInfo('the edit arrived');
return false;
});Questions
A field is undefined although it exists in the game. A packet carries only the data that changed. Armour that did not change is not in the packet.
The edit was not applied and the console shows an error. Most often: the field is not in this packet; the number does not fit the field; an identity or opaque block was changed; both fields and bytes changed in one return.
define gave no fields. The packet was shorter than the layout, or its bits do not split into whole bytes where a bytes type needs them. Check the layout with raw.on.
The handler gets nothing. Check direction and the ID. stats() shows whether the client sees such packets at all.