XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using static XFEEDToolBox.Plugin.JsonWire;

namespace XFEEDToolBox.Plugin;

internal static unsafe partial class Navigation
{
    private static bool OriginalServiceBinding(in Snapshot frame, nuint backend, uint market)
    {
        try
        {
            if (backend == 0)
            {
                var player = Pointer(frame.inputRoot + 0x2E8); var dock = LocalDocking(frame); var station = Pointer(dock + 0x4E0);
                var stationData = station != 0 ? RegisteredComponent(Pointer(station + 0xC8) - 0x30, Read<uint>(image + 0x5F44D10)) : 0;
                return CommerceDocked(frame, market) && player != 0 && Pointer(player) == image + 0x52A0258 && stationData != 0 && Pointer(stationData) == image + 0x53258F0;
            }
            if (Pointer(backend) != image + 0x5240AB8 || Pointer(backend - 0x58) != image + 0x5240988 || Pointer(backend - 0x50) != image + 0x52409B8 || Pointer(backend + 0x110) != Pointer(frame.inputRoot + 0x2E8) || !CommerceDocked(frame, market)) return false;
            var boundDock = LocalDocking(frame); var boundStation = Pointer(boundDock + 0x4E0);
            var data = RegisteredComponent(Pointer(boundStation + 0xC8) - 0x30, Read<uint>(image + 0x5F44D10));
            return data != 0 && Pointer(backend + 0xA0) == data && Pointer(data) == image + 0x53258F0;
        }
        catch { return false; }
    }
    private static bool StartOriginalServiceRead(in Snapshot frame, ref CommerceReadRequest work)
    {
        try
        {
            if (work.kind != 3 || !OriginalServiceBinding(frame, work.maintenance, work.market)) return false;
            if (work.maintenance == 0)
            {
                var route = GameRoute(frame, out _); var context = route != 0 ? route - 0x50 : 0;
                if (context == 0 || Pointer(Pointer(context)) != image + 0x541C70) return false;
                var instance = (nuint)Call(image + 0x53A690, 0xF8); if (instance == 0) return false;
                ClearServiceMemory(instance, 0xF8);
                Call(image + 0x33FCC50, instance + 0xA8, context);
                Call(image + 0x99F4F0, instance, 1, image + 0x5240670);
                Write(instance, image + 0x511F9D0); work.request = instance;
                Call(image + 0x340E980, instance); return true;
            }
            var request = work.maintenance + 0x130;
            if (Pointer(request) != image + 0x511F9D0) return false;
            var state = Read<uint>(request + 0x3C);
            if (state is not (1 or 2)) Call(image + 0x1E67540, work.maintenance);
            work.request = request; work.borrowed = true; return true;
        }
        catch (Exception error) { work.error = CommerceExceptionCode(error); return false; }
    }
    private static nuint OriginalMaintenanceAddress(JsonElement request)
    {
        var value = request.Str("maintenanceAddress", "0x0");
        if (value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) value = value[2..];
        return checked((nuint)ulong.Parse(value, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture));
    }
    private static JsonObject OriginalServiceReadCall(JsonElement request, in Snapshot frame)
    {
        var market = request.Required("marketId").GetUInt32(); var backend = OriginalMaintenanceAddress(request);
        if (!Enabled() || !inGame || !frame.valid || !frame.healthValid || frame.hullFraction<=0 || frame.healthEmergency || GetTickCount64() - frame.tick > 200 || !OriginalServiceBinding(frame, backend, market)) throw new InvalidOperationException("Fresh healthy docked ship and its exact original maintenance component required");
        lock (commerceReadLock)
        {
            if (commerceRead.generation != 0 && commerceRead.state < 3) throw new InvalidOperationException("Original commerce request already pending");
            commerceRead = NewCommerceRead(frame, market, ++commerceReadGeneration); commerceRead.kind = 3; commerceRead.maintenance = backend; commerceRead.queued = GetTickCount64(); commerceReadBody = "";
            return Obj(("generation", commerceRead.generation), ("queued", true), ("mutationsSent", 0));
        }
    }
    private struct OriginalFuelState { public float main, capacity, reserve, reserveCapacity; public bool verified; }
    private static OriginalFuelState ReadOriginalFuel(in Snapshot frame)
    {
        OriginalFuelState result = default;
        try
        {
            var fuel = RegisteredComponent(Pointer(frame.life + 0xC8) - 0x30, Read<uint>(image + 0x5F45128));
            if (fuel == 0 || Pointer(fuel) != image + 0x550E8A8) return result;
            var table = Pointer(fuel);
            if (Pointer(table + 0x58) != image + 0x380B8A0 || Pointer(table + 0x60) != image + 0x380B8E0 || Pointer(table + 0x90) != image + 0x380B920) return result;
            result.main = CallFloat(image + 0x380B8A0, fuel); result.capacity = CallFloat(image + 0x380B8E0, fuel);
            result.reserve = CallFloat(Pointer(table + 0x88), fuel); result.reserveCapacity = CallFloat(image + 0x380B920, fuel);
            result.verified = float.IsFinite(result.main) && float.IsFinite(result.capacity) && float.IsFinite(result.reserve) && float.IsFinite(result.reserveCapacity) && result.capacity > 0 && result.capacity <= 1024 && result.main >= 0 && result.main <= result.capacity + .001f && result.reserveCapacity > 0 && result.reserveCapacity < 16 && result.reserve >= 0 && result.reserve <= result.reserveCapacity + .001f;
        }
        catch { }
        return result;
    }
    private static JsonObject OriginalServiceInventoryCall(in Snapshot frame)
    {
        var fuel = ReadOriginalFuel(frame); var inventory = ReadCommerceShipInventory(frame);
        if (!fuel.verified || !inventory.verified) throw new InvalidOperationException("Actual original fuel/cargo/wallet observation unavailable");
        return Obj(("verified", true), ("fuelLevel", fuel.main), ("fuelCapacity", fuel.capacity), ("reserveLevel", fuel.reserve), ("reserveCapacity", fuel.reserveCapacity), ("credits", inventory.credits), ("cargoCount", inventory.count));
    }
    private static void ClearServiceMemory(nuint at, int length) => Platform.WriteBytes(at, new byte[length]);
    private static void WriteServiceMemory(nuint at, ReadOnlySpan<byte> value) => Platform.WriteBytes(at, value);
    private static nuint OriginalServiceText(byte* body, nuint length)
    {
        var text = (nuint)Call(image + 0x541380, length + 21); if (text == 0) return 0;
        Write(text, (ulong)length); Write(text + 8, (ulong)length); Write<int>(text + 16, 1);
        WriteServiceMemory(text + 20, new ReadOnlySpan<byte>(body, checked((int)length))); Write<byte>(text + 20 + length, 0); return text;
    }
    private static byte* AlignServiceScratch(byte* value) => (byte*)(((nuint)value + 15) & ~(nuint)15);
    private static bool StartOriginalRearmRequest(ref CommerceReadRequest work, nuint instance)
    {
        nuint query = 0, payload = 0, domain = 0;
        var bytes = stackalloc ulong[4]; var headers = stackalloc ulong[4]; new Span<ulong>(bytes, 4).Clear(); new Span<ulong>(headers, 4).Clear();
        try
        {
            Call(image + 0x33FDA40, instance + 0xA8, (ulong)(nuint)(&query));
            if (query == 0 || Read<ulong>(query) > 16384 || work.servicePayloadLength == 0 || work.servicePayloadLength >= 4096) return false;
            var length = Read<ulong>(query); ReadOnlySpan<byte> finalCredits = "&finalCredits="u8;
            Call(image + 0x1FC5A0, (ulong)(nuint)(&query), length + (ulong)finalCredits.Length); WriteServiceMemory(query + 20 + (nuint)length, finalCredits);
            Call(image + 0x53CD20, (ulong)(nuint)(&query), work.creditsBefore - work.price);
            length = Read<ulong>(query); ReadOnlySpan<byte> cost = "&cost="u8;
            Call(image + 0x1FC5A0, (ulong)(nuint)(&query), length + (ulong)cost.Length); WriteServiceMemory(query + 20 + (nuint)length, cost);
            Call(image + 0x53CD20, (ulong)(nuint)(&query), work.price);
            fixed (byte* value = work.servicePayload) payload = OriginalServiceText(value, work.servicePayloadLength);
            if (payload == 0) return false;
            Call(image + 0x5C0B60, (ulong)(nuint)bytes, (ulong)(nuint)(&payload));
            var provider = Pointer(instance + 0xB8); if (provider == 0 || !InImage(Pointer(Pointer(provider) + 0x70))) return false;
            Call(Pointer(Pointer(provider) + 0x70), provider, (ulong)(nuint)(&domain)); if (domain == 0) return false;
            work.mutationSent = true;
            Call(image + 0x9A5040, instance, (ulong)(nuint)(&domain), (ulong)(nuint)(&query), (ulong)(nuint)bytes, (ulong)(nuint)headers, 0, 1); return true;
        }
        finally
        {
            if (domain != 0 && Platform.AtomicDecrement(domain + 0x10) == 0)
            {
                var release = Pointer(Pointer(domain + 8)); if (InImage(release)) Call(release, domain + 8, 1);
            }
            if (query != 0) Call(image + 0x204010, (ulong)(nuint)(&query));
            if (payload != 0) Call(image + 0x204010, (ulong)(nuint)(&payload));
            if (bytes[3] != 0) Call(image + 0x55B910, bytes[3]);
        }
    }
    private static bool StartOriginalServiceMutation(in Snapshot frame, ref CommerceReadRequest work, nuint context)
    {
        try
        {
            if (work.kind < 4 || work.kind > 7 || work.mutationSent || !OriginalServiceBinding(frame, work.maintenance, work.market)) return false;
            var inventory = ReadCommerceShipInventory(frame); var fuel = ReadOriginalFuel(frame);
            if (!inventory.verified || !fuel.verified || inventory.count != work.totalBefore || inventory.credits != work.creditsBefore || inventory.credits < work.price || Math.Abs(fuel.capacity - work.fuelTarget) > .001f || Math.Abs(fuel.reserveCapacity - work.reserveTarget) > .001f) return false;
            var instance = (nuint)Call(image + 0x53A690, 0xF8); if (instance == 0) return false;
            ClearServiceMemory(instance, 0xF8); Call(image + 0x33FCC50, instance + 0xA8, context);
            Call(image + 0x99F4F0, instance, 3, image + (work.kind == 4 ? (nuint)0x5247E00 : work.kind == 7 ? (nuint)0x5240650 : 0x5247E18));
            Write(instance, image + (work.kind == 7 ? (nuint)0x511F9D0 : 0x51A4640)); work.request = instance;
            if (work.kind == 7) return StartOriginalRearmRequest(ref work, instance);
            work.mutationSent = true;
            if (work.kind == 4) Call(image + 0x344E350, instance, F32(fuel.capacity), F32(fuel.reserveCapacity), inventory.credits - work.price);
            else
            {
                nuint emptyPayload = 0;
                Call(image + 0x344E600, instance, 0, 0, work.kind == 6 ? 1UL : 0, inventory.credits - work.price, (ulong)(nuint)(&emptyPayload), work.kind == 5 ? 1UL : 0);
            }
            return true;
        }
        catch (Exception error) { work.error = CommerceExceptionCode(error); return false; }
    }
    private static string RearmSlot(in RearmTarget target)
    {
        fixed (byte* value = target.slot) { var count = 0; while (count < 48 && value[count] != 0) count++; return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(value, count)); }
    }
    private static bool ValidateOriginalServiceMutation(in CommerceReadRequest work, byte* body, nuint length)
    {
        if (work.kind == 7)
        {
            using var document = JsonDocument.Parse(new ReadOnlySpan<byte>(body, checked((int)length)).ToArray()); var response = document.RootElement;
            if (response.TryGetProperty("error", out _) || !response.TryGetProperty("credits", out var credits) || credits.GetUInt64() != work.creditsBefore - work.price || !response.TryGetProperty("ship", out var ship) || !ship.TryGetProperty("modules", out var modules) || modules.ValueKind != JsonValueKind.Object || work.rearmCount == 0) return false;
            for (var index = 0; index < work.rearmCount; index++)
            {
                var expected = work.rearm[index];
                if (!modules.TryGetProperty(RearmSlot(expected), out var slot) || !slot.TryGetProperty("module", out var module) || !module.TryGetProperty("ammo", out var ammo) || ammo.Required("clip").GetInt32() != expected.clip || ammo.Required("hopper").GetInt32() != expected.hopper) return false;
            }
            return true;
        }
        return work.kind >= 4 && work.kind <= 6 && body != null && length > 0 && length <= 65536 && body[0] == (byte)'<';
    }
    private static bool ApplyOriginalRearmMutation(in Snapshot frame, ref CommerceReadRequest work, byte* body, nuint length)
    {
        try
        {
            if (!OriginalServiceBinding(frame, work.maintenance, work.market) || frame.entity != work.entity || frame.life != work.life || controllerEpoch != work.epoch) return false;
            var inventory = ReadCommerceShipInventory(frame);
            if (!inventory.verified || inventory.credits != work.creditsBefore || inventory.count != work.totalBefore || GameRoute(frame, out var pilot) == 0) return false;
            var root = Pointer(frame.life + 0xC8) - 0x30;
            var loadout = RegisteredComponent(root, Read<uint>(image + 0x5F2F274)); var optional = RegisteredComponent(root, Read<uint>(image + 0x5F771A4));
            var wallet = RegisteredComponent(Pointer(pilot + 0xC8) - 0x30, Read<uint>(image + 0x5F59D90));
            if (loadout == 0 || Pointer(loadout) != image + 0x559CF58 || wallet == 0 || Pointer(wallet) != image + 0x5295868 || Pointer(Pointer(wallet) + 0xA0) != image + 0x2591C70) return false;
            var text = OriginalServiceText(body, length); if (text == 0) return false;
            var scratch = stackalloc byte[32 + 16 + 16 + 15]; var document = AlignServiceScratch(scratch); var view = document + 32; var ship = view + 16; new Span<byte>(document, 64).Clear(); var initialized = false;
            try
            {
                Call(image + 0x4C0CAC0, (ulong)(nuint)document, 0, 0); initialized = true;
                Call(image + 0x4C10BD0, (ulong)(nuint)document, (ulong)(nuint)view, (ulong)(nuint)(&text));
                fixed (byte* name = "ship\0"u8)
                {
                    if ((byte)Call(image + 0x4C10AD0, (ulong)(nuint)view) == 0 || (byte)Call(image + 0x4C10530, (ulong)(nuint)view, (ulong)(nuint)name) == 0) return false;
                    Call(image + 0x4C0FBA0, (ulong)(nuint)view, (ulong)(nuint)ship, (ulong)(nuint)name);
                }
                Call(image + 0x1E4ADB0, (ulong)(nuint)ship, loadout, optional);
                Call(image + 0x2591C70, wallet, (ulong)(nuint)(&text), unchecked((ulong)-(long)work.price), 0, 0);
                var after = ReadCommerceShipInventory(frame); work.serviceReplyVerified = true; work.creditsResult = work.creditsBefore - work.price;
                work.clientApplied = after.verified && after.credits == work.creditsResult && after.count == work.totalBefore; return work.clientApplied;
            }
            finally { if (initialized) Call(image + 0x4C0CB40, (ulong)(nuint)document); Call(image + 0x204010, (ulong)(nuint)(&text)); }
        }
        catch (Exception error) { work.error = CommerceExceptionCode(error); return false; }
    }
    private static bool OriginalDomField(byte* node, string name, byte* value)
    {
        var key = Encoding.UTF8.GetBytes(name + '\0');
        fixed (byte* text = key) Call(image + 0x71C610, (ulong)(nuint)node, (ulong)(nuint)value, (ulong)(nuint)text);
        return (byte)Call(image + 0x71E990, (ulong)(nuint)value) != 0;
    }
    private static bool OriginalDomFuelNumber(byte* node, string name, out float value)
    {
        var scratch = stackalloc byte[31]; var field = AlignServiceScratch(scratch); new Span<byte>(field, 16).Clear(); value = 0;
        if (!OriginalDomField(node, name, field)) return false;
        value = CallFloat(image + 0x71D730, (ulong)(nuint)field, F32(-1)); return float.IsFinite(value) && value >= 0;
    }
    private static bool ApplyOriginalServiceMutation(in Snapshot frame, ref CommerceReadRequest work, byte* body, nuint length)
    {
        if (work.kind == 7) return ApplyOriginalRearmMutation(frame, ref work, body, length);
        try
        {
            if (!OriginalServiceBinding(frame, work.maintenance, work.market) || frame.entity != work.entity || frame.life != work.life || controllerEpoch != work.epoch) return false;
            var inventory = ReadCommerceShipInventory(frame);
            if (!inventory.verified || inventory.count != work.totalBefore || inventory.credits != work.creditsBefore || GameRoute(frame, out var pilot) == 0) return false;
            var wallet = RegisteredComponent(Pointer(pilot + 0xC8) - 0x30, Read<uint>(image + 0x5F59D90)); var fuel = RegisteredComponent(Pointer(frame.life + 0xC8) - 0x30, Read<uint>(image + 0x5F45128));
            if (wallet == 0 || Pointer(wallet) != image + 0x5295868 || Pointer(Pointer(wallet) + 0x80) != image + 0x2591A10 || fuel == 0 || Pointer(fuel) != image + 0x550E8A8) return false;
            var text = OriginalServiceText(body, length); if (text == 0) return false;
            var scratch = stackalloc byte[64 + 16 * 6 + 15]; var document = AlignServiceScratch(scratch); var root = document + 64; var rootView = root + 16; var prices = rootView + 16; var fuelView = prices + 16; var creditView = fuelView + 16; var costView = creditView + 16; new Span<byte>(document, 64 + 16 * 6).Clear(); var documentInitialized = false;
            try
            {
                Call(image + 0x719D40, (ulong)(nuint)document, 0, 0); documentInitialized = true;
                if ((byte)Call(image + 0x71F130, (ulong)(nuint)document, (ulong)(nuint)(&text), 0, 0) == 0) return false;
                var handle = Call(image + 0x56E550, (ulong)(nuint)root, (ulong)(nuint)document); Call(image + 0x71FF00, handle, (ulong)(nuint)rootView);
                if (!OriginalDomField(rootView, "prices", prices) || !OriginalDomField(rootView, "credits", creditView)) return false;
                var serverCredits = unchecked((long)Call(image + 0x71D7A0, (ulong)(nuint)creditView, ulong.MaxValue));
                if (serverCredits < 0 || (ulong)serverCredits != work.creditsBefore - work.price) return false;
                if (work.kind != 4)
                {
                    var repairScratch = stackalloc byte[16 * 3 + 15]; var repair = AlignServiceScratch(repairScratch); var integrity = repair + 16; var wear = integrity + 16; new Span<byte>(repair, 48).Clear();
                    var repairValue = prices; if (OriginalDomField(prices, "repair", repair)) repairValue = repair;
                    var repaired = repairValue;
                    if (work.kind == 6) { if (!OriginalDomField(repairValue, "shipIntegrityCosts", integrity)) return false; repaired = integrity; }
                    if (!OriginalDomField(repaired, "costToRepair", costView) || unchecked((long)Call(image + 0x71D7A0, (ulong)(nuint)costView, ulong.MaxValue)) != 0) return false;
                    if (work.kind == 6 && (!OriginalDomField(integrity, "wear", wear) || unchecked((long)Call(image + 0x71D7A0, (ulong)(nuint)wear, ulong.MaxValue)) != 0)) return false;
                    var player = Pointer(frame.inputRoot + 0x2E8); if (player == 0 || Pointer(player) != image + 0x52A0258) return false;
                    Call(image + 0x1E489C0, (ulong)(nuint)repairValue, player); Call(image + 0x2591A10, wallet, (ulong)(nuint)(&text), unchecked((ulong)-(long)work.price), 0, 1);
                    var after = ReadCommerceShipInventory(frame); work.creditsResult = (ulong)serverCredits; work.serviceReplyVerified = true;
                    work.clientApplied = after.verified && after.count == work.totalBefore && after.credits == work.creditsResult; return work.clientApplied;
                }
                var value = prices; if (OriginalDomField(prices, "fuel", fuelView)) value = fuelView;
                if (!OriginalDomFuelNumber(value, "fuelLevel", out work.fuelResult) || !OriginalDomFuelNumber(value, "reserveLevel", out work.reserveResult) || !OriginalDomFuelNumber(value, "fuelCapacity", out work.fuelCapacityResult) || !OriginalDomFuelNumber(value, "reserveCapacity", out work.reserveCapacityResult) || Math.Abs(work.fuelResult - work.fuelTarget) > .001f || Math.Abs(work.reserveResult - work.reserveTarget) > .001f || Math.Abs(work.fuelCapacityResult - work.fuelTarget) > .001f || Math.Abs(work.reserveCapacityResult - work.reserveTarget) > .001f || !OriginalDomField(value, "costToRefuel", costView)) return false;
                var nextCost = unchecked((long)Call(image + 0x71D7A0, (ulong)(nuint)costView, ulong.MaxValue)); if (nextCost != 0) return false;
                work.nextRefuelCost = 0; work.creditsResult = (ulong)serverCredits; work.serviceReplyVerified = true;
                if (work.maintenance != 0) Call(image + 0x1E46AF0, work.maintenance, (ulong)(nuint)value, fuel);
                else { Call(Pointer(Pointer(fuel) + 0x70), fuel, F32(work.fuelResult)); Call(Pointer(Pointer(fuel) + 0xA0), fuel, F32(work.reserveResult)); }
                Call(image + 0x2591A10, wallet, (ulong)(nuint)(&text), unchecked((ulong)-(long)work.price), 0, 0);
                var actual = ReadOriginalFuel(frame); var finalInventory = ReadCommerceShipInventory(frame);
                work.clientApplied = actual.verified && finalInventory.verified && finalInventory.count == work.totalBefore && finalInventory.credits == work.creditsBefore - work.price && Math.Abs(actual.main - work.fuelTarget) < .001f && Math.Abs(actual.reserve - work.reserveTarget) < .001f;
            }
            finally { if (documentInitialized) Call(image + 0x71A8D0, (ulong)(nuint)document); Call(image + 0x204010, (ulong)(nuint)(&text)); }
            return work.clientApplied;
        }
        catch (Exception error) { work.error = CommerceExceptionCode(error); return false; }
    }
    private static JsonObject OriginalServiceMutationCall(JsonElement request, in Snapshot frame)
    {
        var market = request.Required("marketId").GetUInt32(); var backend = OriginalMaintenanceAddress(request); var key = request.Required("operationKey").GetString()!;
        var kind = request.Required("action").GetString() switch { "refuel" => 4u, "repair" => 5u, "integrity" => 6u, "rearm" => 7u, _ => 0u };
        if (kind == 0 || !CommerceOperationKey(key)) throw new InvalidOperationException("Identified original station service operation required");
        if (!Enabled() || !inGame || !frame.valid || !frame.healthValid || frame.hullFraction<=0 || frame.healthEmergency || GetTickCount64() - frame.tick > 200 || !OriginalServiceBinding(frame, backend, market)) throw new InvalidOperationException("Fresh healthy exact docked maintenance binding required");
        var inventory = ReadCommerceShipInventory(frame); var fuel = ReadOriginalFuel(frame); if (!inventory.verified || !fuel.verified) throw new InvalidOperationException("Original fuel, cargo and wallet observation required");
        lock (commerceReadLock)
        {
            if (commerceOperationKeys.TryGetValue(key, out var previous)) { if (previous != commerceRead.generation) throw new InvalidOperationException("Service already submitted; reconcile its actual receipt"); return Obj(("generation", previous), ("duplicate", true)); }
            var snapshot=request.TryGetProperty("quoteGeneration",out var quoteGeneration);
            var current=snapshot?ServiceQuoteMatches(serviceQuoteSnapshot,frame,backend,market,quoteGeneration.GetUInt64(),kind,GetTickCount64(),controllerEpoch)
                :commerceRead.kind==3&&commerceRead.maintenance==backend&&commerceRead.market==market&&commerceRead.entity==frame.entity&&commerceRead.life==frame.life&&GetTickCount64()-commerceRead.observed<=30000;
            if(commerceReconciliationRequired||commerceOperationKeys.Count>=4096||commerceRead.state!=3||!current)throw new InvalidOperationException("Read fresh original service prices before refuelling");
            using var document = JsonDocument.Parse(snapshot?serviceQuoteSnapshot.body!:commerceReadBody); var prices = document.RootElement.Required("prices");
            var quote = kind == 4 ? prices.Required("fuel") : kind == 5 ? prices.Required("repair") : kind == 7 ? prices.Required("ammunition") : prices.Required("repair").Required("shipIntegrityCosts");
            var quoted = quote.Required(kind == 4 ? "costToRefuel" : kind == 7 ? "costToRearm" : "costToRepair").GetUInt32(); var cost = quoted != 0 && kind is 5 or 7 ? Math.Max(quoted, 10u) : quoted;
            var production=request.Bool("production");var reserve=production?request.Required("reserveCredits").GetUInt64():0;
            if (cost == 0 || !production&&cost > 50000 || inventory.credits < reserve || inventory.credits-reserve < cost) throw new InvalidOperationException("Current original service quote or budget does not permit this operation");
            if (kind == 4 && (Math.Abs(quote.Required("fuelCapacity").GetSingle() - fuel.capacity) > .001f || Math.Abs(quote.Required("reserveCapacity").GetSingle() - fuel.reserveCapacity) > .001f || Math.Abs(quote.Required("fuelLevel").GetSingle() - fuel.main) > .05f || Math.Abs(quote.Required("reserveLevel").GetSingle() - fuel.reserve) > .05f)) throw new InvalidOperationException("Quoted fuel quantities no longer match this ship");
            var generation = ++commerceReadGeneration; var next = NewCommerceRead(frame, market, generation);
            next.kind = kind; next.maintenance = backend; next.price = cost; next.creditsBefore = inventory.credits; next.totalBefore = checked((int)inventory.count); next.fuelTarget = fuel.capacity; next.reserveTarget = fuel.reserveCapacity; next.queued = GetTickCount64();
            if (kind == 7)
            {
                var payload = new StringBuilder();
                foreach (var item in quote.Required("moduleCosts").EnumerateObject())
                {
                    var slot = item.Name; var module = item.Value; if (module.Required("costToRearm").GetInt32() <= 0) continue;
                    if (slot.Length == 0 || slot.Length >= 48 || slot.Any(c => !(c is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or >= '0' and <= '9' or '_')) || next.rearmCount >= 64) throw new InvalidOperationException("Original rearm slot identity exceeds bounds");
                    var clip = module.Required("maxRoundsInClip").GetInt32(); var hopper = module.Required("maxRoundsInHopper").GetInt32(); if (clip < 0 || hopper < 0 || clip > 1000000 || hopper > 1000000) throw new InvalidOperationException("Original rearm quantity exceeds bounds");
                    ref var target = ref next.rearm[(int)next.rearmCount++];
                    fixed (byte* name = target.slot) Encoding.UTF8.GetBytes(slot, new Span<byte>(name, 48)); target.clip = clip; target.hopper = hopper;
                    if (payload.Length != 0) payload.Append('&'); payload.Append("ammo[").Append(slot).Append("]=").Append(clip.ToString(CultureInfo.InvariantCulture)).Append(',').Append(hopper.ToString(CultureInfo.InvariantCulture));
                }
                var encoded = Encoding.UTF8.GetBytes(payload.ToString());
                if (next.rearmCount == 0 || encoded.Length >= 4096) throw new InvalidOperationException("Original rearm payload is empty or exceeds bounds");
                new ReadOnlySpan<byte>(encoded).CopyTo(new Span<byte>(next.servicePayload, 4096)); next.servicePayloadLength = (uint)encoded.Length;
            }
            if(snapshot)serviceQuoteSnapshot.consumed|=1u<<(int)kind;
            commerceRead = next; commerceOperationKeys.Add(key, generation); commerceReadBody = "";
            return Obj(("generation", generation), ("queued", true), ("cost", cost));
        }
    }
}