C# API reference
Public types and members of the s&box Network Storage library, generated from its source and XML documentation comments. Most games only need NetworkStorage: Configure once, then call endpoints, documents and queries.
Core
enum EntryKind
_entriesif_entries_version
class JsonHelpers
Shared JSON deserialization helpers for Network Storage responses. Handles type coercion (string → number), missing keys, and fallback defaults.
public static int GetInt(JsonElement el, string key, int fallback)Get an integer from a JSON element, with fallback.
public static float GetFloat(JsonElement el, string key, float fallback)Get a float from a JSON element, with fallback.
public static string GetString(JsonElement el, string key, string fallback)Get a string from a JSON element, with fallback.
public static bool GetBool(JsonElement el, string key, bool fallback)Get a bool from a JSON element, with fallback.
class NetLog
Static ring buffer that captures Network Storage events for in-game debug windows. Used internally by NetworkStorage and available for game code to log custom events.
public static void Request(string tag, string message)public static void Response(string tag, string message)public static void Warning(string tag, string message)public static void Error(string tag, string message)public static void Info(string tag, string message)public static void Clear()class NetworkStorage
public static void AutoConfigure()Auto-configure from network-storage.credentials.json. Called automatically on first API use.
class NetworkStorage
Network Storage client for sboxcool.com.
Auto-configures from network-storage.credentials.json on first use. You can also call Configure() manually to override.
public static string BaseUrlBase API URL (no trailing slash).
public static string ApiVersionAPI version prefix.
public const string LibraryVersion = ""Library SemVer, independent of the s&box package and game revisions.
public const string MinServerVersion = ""Oldest self-hosted server baseline; newer features require capability checks.
public static string PackageVersionLibrary version reported to analytics. Retained as an LTS public API.
public static string ProjectIdYour project ID from the sboxcool.com dashboard.
public static string ApiKeyYour public API key (sbox_ns_ prefix).
public static bool IsConfiguredTrue after Configure() or auto-config has loaded valid credentials.
public static string CdnUrlOptional CDN URL for storage reads.
public static string ApiRootThe full versioned API root, e.g. https://api.sboxcool.com/v3.
public static bool ProxyEnabledWhether non-host clients route API calls through the game host.
public static bool EnableAuthSessionsProject flag for fast auth sessions.
public static bool EnableEncryptedRequestsProject flag for encrypted Network Storage requests.
public static string PublishTargetRuntime publish target for Network Storage resources ("live" or staged "next").
public static Func<string, string, string, string, Task<string>> RequestProxyDelegate for proxying endpoint calls through the game host.
public static Func<string, string, string, string, Task<string>> DocumentProxyDelegate for proxying document reads through the game host.
public static bool IsHostTrue if this client is the network host or single-player.
public static void Configure(string projectId, string apiKey, string baseUrl = null, string apiVersion = null, string cdnUrl = null, string publishTarget = null)Configure the client manually. Call once at game startup.
public static void SetPublishTarget(string publishTarget)Override the runtime publish target used for endpoint/storage/value requests.
public static void ResetAutoConfigureFlag()Reset the auto-configure guard so AutoConfigure() can retry.
class NetworkStorage
public static void EnsureConfigured()class NetworkStorage
Helpers for writing revision metadata to lobbies. Call BuildLobbyMetadata when creating a lobby to stamp revision tracking keys that other clients can use to discover lobbies running the latest game version.
Key schema (short names for efficient network transfer): ns_rev — RuntimeRevisionId (0 for editor/local sessions) ns_stale — 1 if outdated, 0 if current ns_grace_end — Grace period end unix timestamp, or 0 ns_mig — 1 if this lobby supports migration, 0 otherwise ns_mig_rev — Migration target revision, or 0 ns_src — Source lobby ID (set when created via "Create New Game")
public static Dictionary<string, string> BuildLobbyMetadata(long? migrationRevision = null, string sourceLobbyId = null)Build a lobby metadata dictionary with revision tracking keys. Pass the result to your lobby creation API (e.g. lobby.SetMetadata).
migrationRevisionTarget revision for migration, or null.
sourceLobbyIdPrevious lobby ID (for "Create New Game" flow), or null.
public static bool IsLobbyOnCurrentRevision(Dictionary<string, string> metadata)Check whether a lobby's metadata indicates it's running the latest revision. Useful for filtering stale lobbies.
public static bool IsLobbyStale(Dictionary<string, string> metadata)Check whether a lobby's metadata says it's stale (outdated revision).
class NetworkStorage
public static bool TryGetLastEndpointError(string slug, out string code, out string message)class NetworkStorage
public static event Action<RevisionOutdatedData> OnRevisionOutdatedFired when the load-profile endpoint reports an outdated revision, or when TestFireRevisionOutdated is called. Subscribe to show custom in-game UI for revision warnings.
class NetworkStorage
public static RevisionSettings RevisionSettingsPublic settings for the revision/outdated-session system. Configure these once during game startup.
class NetworkStorage
public static void OpenRevisionOutdatedMessage(Panel parent = null)Open the outdated revision message panel. Requires a parent panel to attach to. If parent is null, a warning is logged and no UI is created, but the OnRevisionOutdated hook still fires.
public static void CloseRevisionOutdatedMessage()Close the outdated revision message panel if it is open.
public static void ToggleRevisionOutdatedMessage(Panel parent = null)Toggle the outdated revision message panel open/closed.
public static async Task RefreshRevisionLobbyListAsync()Refresh the lobby list to find lobbies running the latest revision. This is a stub — game code should override with actual lobby query logic by subscribing to OnRefreshLobbyListRequested.
public static event Action OnRefreshLobbyListRequestedFired when RefreshRevisionLobbyListAsync is called. Game code should subscribe and perform the actual lobby refresh.
public static void TestShowRevisionOutdatedMessage(Panel parent = null)Simulate an outdated revision detection for testing. Creates a fake RevisionOutdatedData with Reason = ManualTest and fires the full UI pipeline: - Updates NetworkStoragePackageInfo state - Fires OnRevisionOutdated for custom hooks - Opens the default message panel (if configured)
Does NOT require the backend to report a mismatch. Bypasses ShowOnlyOnce. Logs clearly that this is a test.
public static void TestFireRevisionOutdated()Fire the OnRevisionOutdated event with test data. Does NOT show the default UI — only fires the event so game code can test custom hooks without interference from the default panel. Logs clearly that this is a test.
class NetworkStorage
class NetworkStorage
class NetworkStorageExtensions
Extension helpers for working with Network Storage JSON responses. Reduces boilerplate when parsing endpoint responses into game objects.
Usage: var ores = response.ReadDictionary( "ores", prop => (float)prop.GetDouble() ); var upgrades = response.ReadStringList( "purchasedUpgrades" ); var level = response.Int( "level", 1 );
public static int Int(this JsonElement el, string key, int fallback = 0)Get an int from a JsonElement, with fallback.
public static float Float(this JsonElement el, string key, float fallback = 0f)Get a float from a JsonElement, with fallback.
public static string Str(this JsonElement el, string key, string fallback = "")Get a string from a JsonElement, with fallback.
public static bool Bool(this JsonElement el, string key, bool fallback = false)Get a bool from a JsonElement, with fallback.
public static List<string> ReadStringList(this JsonElement el, string key)Read a JSON array property as a List of strings. Returns empty list if property missing or wrong type.
public static Dictionary<string, T> ReadDictionary<T>(this JsonElement el, string key, Func<JsonElement, T> converter)Read a JSON object property as a Dictionary with a value converter. Useful for ore inventories: response.ReadDictionary("ores", v => (float)v.GetDouble())
public static List<T> ReadList<T>(this JsonElement el, string key, Func<JsonElement, T> converter)Read a JSON array property as a List with a row converter. Useful for tables: response.ReadList("rows", row => new OreInfo(row))
public static List<string> FindMismatches(this JsonElement serverData, Dictionary<string, (object Local, Func<JsonElement, object> Extract)> fields)Compare local state against a server response and return a list of mismatches. Fields is a dictionary of fieldName → (localValue, serverExtractor).
class NetworkStorageLogConfig
Controls which Network Storage log categories are printed to the console. All categories default to enabled. Call DisableAll() then enable specific ones, or EnableAll() then disable specific ones.
public static bool LogRequestsLog outgoing request details (method, URL, body).
public static bool LogResponsesLog response bodies and status.
public static bool LogTokensLog auth token acquisition and status.
public static bool LogProxyLog proxy RPC traffic (host/client handoff).
public static bool LogErrorsLog errors and warnings (failures, HTTP errors).
public static bool LogConfigLog configuration and startup messages.
public static void EnableAll()Enable all log categories.
public static void DisableAll()Disable all log categories.
class NetworkStorageOutdatedUI
Built-in simple in-game UI for outdated revision warnings. Supports two enforcement modes: - Force Upgrade: Warning with grace countdown, Dismiss button - Allow Continue: Informational with Continue Playing primary
Uses RevisionSettings for configuration. Subscribes to OnRevisionOutdated when AutoOpenOnOutdated is true.
The panel is hidden via CSS class toggling (SetClass("hidden", ...)). A parent panel MUST be provided — the UI does not auto-attach.
public static void ResetState()Reset the popup state. Call this when starting a new game session. This allows the popup to show again even if showPopupOnce is enabled.
public static Panel RootPanelThe parent panel to use when auto-opening the UI. If not set, the library will auto-create a ScreenPanel.
public static bool IsOpenTrue when the panel instance exists and is not hidden.
public static event Action OnCreateNewGameFired when the user clicks "Create New Game".
public static event Action OnJoinNewLobbyFired when the user clicks "Join New Lobby".
public static event Action OnContinuePlayingFired when the user clicks "Continue Playing" (Allow Continue mode).
public static event Action OnDismissFired when the user dismisses the popup.
public static void Open(Panel parent = null)Open the outdated revision window. Uses parent if provided, otherwise falls back to RootPanel. If no parent is available, logs a warning and returns without creating UI.
public static void Close()Dismiss the panel if it is visible.
public override void OnDeleted()public override void Tick()class NetworkStoragePackageInfo
Detects and caches package/revision information from s&box APIs. Used to track which revision is running and to build sync payloads for the sboxcool.com backend.
public static long? CurrentRevisionIdThe revision ID detected for the package ident, if available.
public static long? RuntimeRevisionIdThe revision ID to send with runtime requests. This is only set for published game bundles; editor/local projects do not masquerade as the live revision.
public static long? LatestRevisionIdThe latest published revision ID for the package.
public static string PackageIdentThe full package ident, e.g. "org.game".
public static string OrgIdentThe organization ident, e.g. "hooked_inc".
public static string PackageTitleThe human-readable package title.
public static string PublishStatusThe publish status of the current revision (e.g. "live").
public static string PackageTypeThe package type (e.g. "game", "addon", "map").
public static bool IsEditorContextTrue when running from the editor, an editor local instance, or an active local project.
public static bool IsPublishedGameBundleTrue only when the engine is running an actual published game bundle.
public static string RuntimeClientTypeThe client type sent to Network Storage: "editor", "dedicated", or "game".
public static bool IsDetectedTrue if detection has run and found package info.
public static bool IsOutdatedRevisionLatest revision status: true when running an older revision.
public static int? GraceRemainingMinutesMinutes remaining in the grace period, if applicable.
public static bool GraceExpiredTrue when the grace period has expired.
public static string RevisionActionCurrent enforcement action: "warn", "block_writes", or "block_all".
public static string RevisionMessageHuman-readable message from the server about revision status.
public static long? ServerCurrentRevisionThe server's current (latest) revision ID.
public static int? PolicyGracePeriodMinutesRevision policy synced from server.
public static string PolicyPostGraceActionpublic static bool PolicyForceEndpointUpgradepublic static string PolicyNotifyMessagepublic static bool PolicyShowUpdateOptionspublic static bool PolicyShowPopupOncepublic static bool PolicyShowDefaultMessagepublic static RevisionEnforcementMode EnforcementModeEnforcement mode from server: ForceUpgrade (default) or AllowContinue.
public static event Action<RevisionStatusInfo> OnRevisionStatusChangedFired when revision status changes. Game code can subscribe to show UI.
public static async Task DetectAsync()Detect package and revision info from the current s&box context. Safe to call multiple times — subsequent calls re-detect from scratch.
public static JsonElement BuildSyncPayload()Build the package-sync payload matching the backend contract: POST /v3/manage/:projectId/package-sync
public static void Reset()Clear all cached detection data.
public static void UpdateFromServerResponse(JsonElement response)Extract _revisionStatus from any server response and update static state. Called automatically by ParseResponse on every endpoint call.
class NetworkStorageRevisionConfig
Opt-in configuration for revision enforcement features. All settings default to false — game code must explicitly opt in.
public static bool EnableRevisionWarningUIShow built-in warning UI when an outdated revision is detected.
public static bool EnableAutoDisconnectHostAuto-disconnect the local client when the revision grace period has expired. DANGEROUS: test thoroughly before enabling in production.
public static bool EnableBlockSavesOnOutdatedSet BlockWrites when running an outdated revision. Endpoint code should check this flag before performing writes. DANGEROUS: may cause data loss if callers ignore the flag.
public static bool EnableOutdatedUIEnable the entire outdated revision notification UI system.
public static bool ShowDefaultWindowShow the built-in default warning window.
public static bool ShowOnlyOnceOnly show the warning once per session.
public static float GracePeriodGrace period override (seconds) before showing the warning. 0 = show immediately.
public static bool AutoRefreshLobbyListAuto-refresh the lobby list when revision is outdated.
public static float LobbyRefreshIntervalInterval in seconds between lobby list refreshes.
class NetworkStorageRevisionHandler
Wires OnRevisionStatusChanged to concrete actions based on RevisionSettings configuration. Call Initialize once during game startup.
public static bool BlockWritesSet when RevisionSettings has block-saves enabled and the client is running an outdated revision. Endpoint code MUST check this flag before performing write operations.
public static Action<RevisionStatusInfo> OnShowRevisionWarningGame code can assign a handler to receive revision warnings. Useful for showing custom in-game UI when the built-in console logging is not enough.
public static void Initialize()Subscribe to revision status change events. Safe to call multiple times — subsequent calls are no-ops.
class NetworkStorageRevisionInit
Sends a one-time revision-init packet at game startup so the backend knows which revision this client is running. Call once after Configure.
public static RevisionInitResult? LastInitResultCached result from the last successful SendInitAsync call.
public static async Task<RevisionInitResult> SendInitAsync()Send the revision init packet to the backend. Safe to call even when package/revision data is unavailable — the request proceeds without revision headers and the result reflects the gap.
enum RevisionEnforcementMode
How the server enforces revision updates.
ForceUpgradeGrace period countdown, then block saves/all requests.
AllowContinuePlayers can keep playing indefinitely with a notification.
struct RevisionInitResult
Result of the one-time revision init handshake with the backend.
public bool OkTrue when the backend acknowledged the init successfully.
public bool IsOutdatedRevisionTrue when the server reports a newer revision is available.
public long? PlayerRevisionThe revision this client is running, if known.
public long? CurrentRevisionThe latest revision reported by the backend.
public string MessageHuman-readable status or warning message from the server.
struct RevisionOutdatedData
Data from the load-profile endpoint's revision block. Fires OnRevisionOutdated when the server reports the client's revision is outdated.
public RevisionOutdatedData()Creates a default instance.
public long CurrentRevisionIdThe revision the client is running.
public long LatestRevisionIdThe latest revision available on the server.
public bool RevisionOutdatedTrue when the client revision is older than latest.
public int GraceSecondsSeconds remaining in the grace period, or 0.
public long? GraceEndsAtUnixSecondsUnix timestamp when grace ends, or null.
public long ServerUnixSecondsServer's current unix timestamp.
public string SourceSource identifier describing where the detection came from. Typical values: "load-profile", "manual-test", "lobby"
public RevisionOutdatedReason ReasonWhy this revision-outdated event was raised.
public RevisionEnforcementMode EnforcementModeThe enforcement mode from the server. Defaults to ForceUpgrade for backward compatibility.
public string MessageCustom message from the server to display to players.
public string ActionWhat action is currently required: "warn", "block_saves", "block_all".
public bool GraceExpiredTrue when the grace period has expired (from server).
public int? GraceRemainingMinutesMinutes remaining in the grace period (from server), or null if no grace.
public bool ShowUpdateOptionsTrue if the server wants to show update options (Create/Join buttons).
public bool ShowPopupOnceTrue if popup should only show once per session.
public int TimeRemainingSeconds until grace expires (negative if already expired).
public bool IsGraceExpiredTrue when the grace period has fully expired.
enum RevisionOutdatedReason
Why the revision was detected as outdated.
LoadProfileDetectedDetected via the load-profile endpoint response.
ManualTestTriggered manually for testing (no backend required).
LobbyMismatchLobby metadata indicates a different revision.
GraceExpiredGrace period expired, revision is now blocked.
class RevisionSettings
Public settings for the NetworkStorage revision/outdated-session system.
Usage: NetworkStorage.RevisionSettings.ShowDefaultMessage = false;
All settings are static and should be configured once during game startup (e.g. in your game's initialization code).
public bool EnabledEnable revision-outdated detection and hook firing. When false, no detection occurs and no events fire. Default: true
public bool ShowDefaultMessageShow the built-in default "OUTDATED REVISION" message panel when the revision becomes outdated. Set to true to enable the default UI, or leave false and use your own via OnRevisionOutdated. Default: false
public bool ShowOnlyOnceOnly show the default message once per session. If false, the panel re-appears every time load-profile reports the revision is outdated. Default: true
public TimeSpan GracePeriodGrace period before the outdated warning appears. Use Zero to show immediately. Default: TimeSpan.Zero
public bool AutoRefreshLobbiesAuto-refresh the lobby list when the revision is outdated. Default: false
public float LobbyRefreshIntervalInterval in seconds between lobby list refreshes. Only used when AutoRefreshLobbies is true. Default: 10
public bool AllowSpaceToCloseAllow the SPACE key to close the default message panel. Default: true
public bool AutoOpenOnOutdatedAutomatically open the default message panel when the revision becomes outdated. Set to false if you want to control when the UI appears via OpenRevisionOutdatedMessage. Default: true
struct RevisionStatusInfo
Snapshot of revision status, passed to OnRevisionStatusChanged.
public bool IsOutdatedpublic bool GraceExpiredpublic int? GraceRemainingMinutespublic string Actionpublic string Messagepublic long? PlayerRevisionpublic long? CurrentRevisionpublic int? PolicyGracePeriodMinutespublic string PolicyPostGraceActionpublic bool PolicyForceEndpointUpgradepublic string PolicyNotifyMessagepublic bool PolicyShowUpdateOptionspublic bool PolicyShowPopupOncepublic bool PolicyShowDefaultMessagepublic RevisionEnforcementMode EnforcementModeAnalytics
class NetworkStorage
public static Task TrackAnalyticsEvent(string eventType, object payload = null)public static Task TrackAnalyticsWarning(string code, string message = null, object context = null)public static Task TrackAnalyticsError(Exception exception, string code = null, object context = null)public static Task TrackAnalyticsError(string code, string message = null, string stack = null, object context = null)public static Task TrackSessionStart(object context = null)public static Task TrackSessionHeartbeat(double sessionSeconds = 0, object context = null, object fps = null)public static Task TrackSessionEnd(double durationSeconds = 0, object context = null)class NetworkStorage
public static bool EnablePlayerAnalyticspublic static bool AnalyticsCaptureSessionspublic static bool AnalyticsCaptureWarningspublic static bool AnalyticsCaptureErrorspublic static bool AnalyticsCaptureLocalWarningspublic static bool AnalyticsCaptureLocalErrorspublic static bool AnalyticsCaptureEndpointDiagnosticspublic static bool AnalyticsManagedLibraryEventspublic static bool AnalyticsManagedPerformancepublic static bool AnalyticsManagedNetworkpublic static bool AnalyticsManagedVoicepublic static bool AnalyticsManagedInputFocuspublic static bool AnalyticsManagedScenepublic static bool AnalyticsManagedRuntimepublic static bool AnalyticsManagedRevisionpublic static bool AnalyticsManagedSystemInfopublic static bool AnalyticsRetainErrorStacksclass NetworkStorageAnalytics
Convenience facade for Player Analytics. Methods forward to NetworkStorage so projects can use either NetworkStorageAnalytics.TrackEvent(...) or NetworkStorage.TrackAnalyticsEvent(...).
public static Task TrackEvent(string eventType, object payload = null)public static Task Warning(string code, string message = null, object context = null)public static Task Error(Exception exception, string code = null, object context = null)public static Task Error(string code, string message = null, string stack = null, object context = null)public static Task SessionStart(object context = null)public static Task SessionHeartbeat(double sessionSeconds = 0, object context = null, object fps = null)public static Task SessionEnd(double durationSeconds = 0, object context = null)Auth
class NetworkStorage
public static async Task<bool> EnsureEndpointAuthAsync(string slug)class NetworkStorage
class NetworkStorage
public static string NetworkStorageSecretKeyDashedConVarpublic static string NetworkStorageSecretKeyConVarpublic static string SboxCoolSecretKeyConVarpublic static string NetworkStorageSecretKeyCamelConVarpublic static string SboxCoolSecretKeyCamelConVarpublic static string NsSecretKeyCamelConVarpublic static string NsSecretKeyConVarpublic static bool HasDedicatedServerSecretKeyTrue when this process is a dedicated server and a runtime endpoint secret key was supplied. The key is never read on clients or listen servers.
public static string DedicatedServerSecretKeySourceWhere the dedicated endpoint secret key was loaded from, without exposing the key.
public static void ConfigureDedicatedServerSecretKey(string secretKey)Manually provide a runtime endpoint secret key. This is accepted only on dedicated servers. Prefer the dedicated launch flag: +network_storage_secret_key sbox_sk_...
class NetworkStorage
public static Task<bool> EnsureDedicatedServerSecretValidatedAsync(string reason = "", bool forceRefresh = false)Validates the configured dedicated-server secret key against the management API. No-op outside dedicated server hosts. Logs success/failure without exposing the key.
Code/Auth/NetworkStorageDedicatedServerSecretValidation.cs:8
Endpoints
class NetworkStorage
class NetworkStorage
class NetworkStorage
class NetworkStorage
class NetworkStorage
class NetworkStorage
public static Task<JsonElement?> CallEndpoint(string slug, object input = null)Call a server endpoint by slug or dashboard endpoint URL. Returns the response body on success, null on any failure.
class NetworkStorage
public static async Task<JsonElement?> GetGameValues()Load all game values (groups + tables).
class NetworkStorage
class NetworkStorage
Frontend helpers for request security metadata used by encrypted Network Storage calls.
public static string CreateEncryptedRequestId()Creates a one-use encrypted request id in "{unixSeconds}_{random}" format. The backend must reject stale or repeated ids before running endpoint logic.
public static bool TryParseEncryptedRequestId(string requestId, out long unixSeconds, out string random)Validates and parses an encrypted request id in "{unixSeconds}_{random6plus}" format.
class NetworkStorage
public static bool RuntimeSecurityConfigLoadedpublic static bool RuntimeEnableAuthSessionspublic static bool RuntimeEnableEncryptedRequestspublic static string RuntimeSecurityConfigVersionpublic static string RuntimeSecurityClientModepublic static string RuntimeSecurityConfigSourcepublic static string LastSecurityConfigDiagnosticspublic static bool IsSecurityConfigMismatchCode(string code)public static async Task<bool> EnsureRuntimeSecurityConfigAsync(string reason = "", bool forceRefresh = false)public static void MarkRuntimeSecurityMismatch(string code, string requestMode = "")public static void ApplyServerExpectedSecurityConfig(string code, JsonElement expected, string expectedConfigVersion = null)class NetworkStorage
class NetworkStorage
Proxy
class NetworkStorage
public static async Task<JsonElement?> CallEndpointAs(string targetSteamId, string clientToken, string slug, object input = null)Call an endpoint on behalf of another player (host only). Requires the client's auth token as proof of consent. Sends: host auth (Facepunch-verified) + client token + HMAC proxy signature scoped to this project + endpoint to prevent cross-server replay.
public static async Task<JsonElement?> GetDocumentAs(string targetSteamId, string clientToken, string collectionId, string documentId = null)Read a document on behalf of another player (host only). Requires the client's auth token as proof of consent.
class NetworkStorage
class NetworkStorageProxyComponent
Bridges NetworkStorage proxy delegates to s&box RPCs.
When proxy mode is enabled (Editor → Network Storage → Settings): - Non-host clients route API calls through this component via [Rpc.Broadcast] - The host receives the request, calls CallEndpointAs / GetDocumentAs, and sends the result back - The client awaits the result via a TaskCompletionSource keyed by request ID
Security: The client's auth token is forwarded to the host, which includes it in the HMAC proxy signature sent to the backend. This proves client consent without requiring the backend to verify the client's token against Facepunch (which fails for non-host clients).
Attach to each player's GameObject via PlayerSpawner.
Storage
class NetworkStorage
public static Task<JsonElement?> SaveDocument(string collectionId, string documentId, object data)Save or replace a collection document. Defaults to the current player's Steam ID. On dedicated servers, a configured secret key is sent automatically so endpoint-only collections can be edited when the key has collection execute permission.
public static Task<JsonElement?> SetDocument(string collectionId, string documentId, object data)Alias for SaveDocument.
public static Task<JsonElement?> UpdateDocument(string collectionId, string documentId, IEnumerable<NetworkStorageOperation> operations)Apply server-side operations to a collection document. This avoids sending the full document and lets the backend validate increments, ledgers, and rate limits.
public static Task<JsonElement?> UpdateDocument(string collectionId, string documentId, params NetworkStorageOperation[] operations)Apply server-side operations to a collection document.
public static Task<JsonElement?> PatchDocument(string collectionId, string documentId, params NetworkStorageOperation[] operations)Alias for UpdateDocument.
public static Task<JsonElement?> DeleteDocument(string collectionId, string documentId = null)Delete a collection document. The backend must have allowRecordDelete enabled for the collection. Defaults to the current player's Steam ID.
public static Task<JsonElement?> ListRecords(string collectionId, string steamId = null)List save-record metadata for a player in a multi-record collection.
public static Task<JsonElement?> CreateRecord(string collectionId, string steamId = null, string recordName = null)Create a save-record entry for a player in a multi-record collection.
public static Task<JsonElement?> DeleteRecord(string collectionId, string recordId, string steamId = null)Delete a save-record entry and its stored document data.
public static Task<JsonElement?> RenameRecord(string collectionId, string recordId, string recordName, string steamId = null)Rename a save-record entry.
class NetworkStorage
public static async Task<JsonElement?> GetDocument(string collectionId, string documentId = null)Read a document from a collection. If documentId is null, uses the current player's Steam ID.
class NetworkStorage
public static Task<JsonElement?> RunQuery(string queryId)Run a dashboard query by ID. Public queries use the public runtime key. On dedicated servers, a configured secret key is sent automatically so secret-gated queries can run without s&box auth tokens.
public static async Task<JsonElement?> GetQuery(string queryId)Alias for RunQuery.
class NetworkStorageOperation
A server-side document mutation for Network Storage collection records. Operations are applied by the backend against the current document, so callers can update counters and arrays without sending a full replacement document.
public string Oppublic string Pathpublic object Valuepublic object Matchpublic string Sourcepublic string Reasonpublic static NetworkStorageOperation Set(string path, object value, string source = null, string reason = null)public static NetworkStorageOperation Increment(string path, double amount, string source = null, string reason = null)public static NetworkStorageOperation Push(string path, object value)public static NetworkStorageOperation Pull(string path, object match)public static NetworkStorageOperation Remove(string path, object value)enum SaveState
PendingCallsSetStateifNetLogvarPendingCallsifelsereturn
class SaveStateTracker
Tracks the save state of endpoint calls for HUD feedback. Wraps NetworkStorage.CallEndpoint with automatic state management and logging.
Usage: var tracker = new SaveStateTracker(); var result = await tracker.Call( "mine-ore", new { ore_id = "moon_ore", kg = 5 } ); if ( result.HasValue ) Apply( result.Value );
Properties: tracker.State → Idle, Saving, Saved, Error tracker.IsBusy → true while any call is in progress tracker.LastError → error message from last failure
public async Task<bool> CallAndApply(string slug, object input, Action applyOptimistic, Action<JsonElement> applyServer, Action revert)Call an endpoint, apply the result to a callback on success, revert on failure. Handles the optimistic update → server confirm → revert pattern.
public void Reset()