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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/XFEEDToolBox

Match native trade validation to the actual market response

A market read supplies inventory and quotes without a wallet field. Accept that schema while retaining native wallet, stock, price, capacity, reserve and full server/client settlement checks. Preserve optional wallet mismatch rejection. Reconcile only unaccepted operation keys from the exact original live process and LoadGame session, retaining the original intent and proof. Package 0.5.17-dev and the SCO extension, retain the original 26 exports and ABI 1, and let the updater finish cleanup after a verified menu process exit. Verified by 33 native fixture checks, 29 trade driver tests, 4 unsubmitted-intent tests, 2 menu-exit tests and a real toolbox-owned 362t Uranium purchase with serverConfirmed/clientApplied true. The toolbox has resumed transport independently.

378d6db
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

15 个文件 +152 -10
Modified .gitignore +1 -0
@@ -33,3 +33,4 @@ XFEEDToolBox/PluginPackage/interaction.json
33 33 !.env.example
34 34
35 35 XFEEDToolBox/PluginPackage/DockingControl/
36 XFEEDToolBox/PluginPackage/CruiseControl/
Modified XFEEDToolBox.Core/Execution/NativeTradeCommandDriver.cs +3 -0
@@ -75,7 +75,10 @@ public sealed class NativeTradeCommandDriver:IConfirmedTradeCommandDriver,IConfi
75 75 if(batchPolicy is not null&&(!hello.TryGetProperty("formalCommodityTrading",out var batches)||batches.ValueKind!=JsonValueKind.True))
76 76 throw new NativeTradeSdkUpgradeRequiredException("游戏当前加载的是旧验收接口;通用跑商需要加载新版原生插件。");
77 77 if(batchPolicy is not null&&!marketClientRefresh)throw new NativeTradeSdkUpgradeRequiredException("当前插件缺少服务器库存与客户端同步核对,尚未启动批量采购。");
78 if(batchPolicy is not null&&(!hello.TryGetProperty("marketWalletOptional",out var walletSchema)||walletSchema.ValueKind!=JsonValueKind.True))
79 throw new NativeTradeSdkUpgradeRequiredException("原生采购入口仍要求行情中不存在的钱包字段,需要加载修正后的原生插件。");
78 80 session=player();ValidateSession();await ensureProtection(token);
81 await NativeUnsubmittedTradeIntents.ReconcileAsync(directory,channel,session,token);
79 82 foreach(var file in Directory.EnumerateFiles(directory,"*.pending.json"))
80 83 if(!File.Exists(file.Replace(".pending.json",".confirmed.json",StringComparison.Ordinal))&&!ExternalTradeSettlement.IsSettled(file,session))throw new InvalidOperationException("存在尚未核对的原生订单,正在等待实际结果;不会重复下单。");
81 84 await gate.WaitAsync(token);try{PublishWallet(await channel.CallAsync(new{op="commerce.inventory"},token));}finally{gate.Release();}
Added XFEEDToolBox.Core/Execution/NativeUnsubmittedTradeIntents.cs +35 -0
@@ -0,0 +1,35 @@
1 using System.Security.Cryptography;
2 using System.Text.Json;
3 using XFEEDToolBox.Core.Models;
4
5 namespace XFEEDToolBox.Core.Execution;
6
7 /// <summary>Reconciles an unaccepted key only in the exact original live game session.</summary>
8 public static class NativeUnsubmittedTradeIntents
9 {
10 public static async Task ReconcileAsync(string directory,IOriginalCommerceChannel channel,PlayerState player,CancellationToken token)
11 {
12 if(!Directory.Exists(directory)||!player.InGame||!player.Docked||!player.CargoReliable||!player.CreditsReliable)return;
13 foreach(var pending in Directory.EnumerateFiles(directory,"*.pending.json"))
14 {
15 var confirmed=pending.Replace(".pending.json",".confirmed.json",StringComparison.Ordinal);
16 if(File.Exists(confirmed))continue;
17 var bytes=await File.ReadAllBytesAsync(pending,token);using var document=JsonDocument.Parse(bytes);var row=document.RootElement;
18 if(row.GetProperty("channel").GetString()!=channel.Identity||row.GetProperty("CommanderId").GetString()!=player.CommanderId
19 ||row.GetProperty("CurrentShipId").GetInt64()!=player.CurrentShipId||row.GetProperty("LoadGameAt").GetDateTimeOffset()!=player.LoadGameAt)continue;
20 var key=row.GetProperty("operationKey").GetString()!;
21 var status=await channel.CallAsync(new{op="commerce.operation.status",operationKey=key},token);
22 // The native map retains every accepted key for this process's
23 // lifetime. A new process/session may never use absence as proof.
24 if(status.GetProperty("known").GetBoolean()||status.GetProperty("mutationsSent").GetInt32()!=0)continue;
25 var before=row.GetProperty("intent").GetProperty("before");
26 var current=await channel.CallAsync(new{op="commerce.inventory"},token);
27 if(!current.GetProperty("verified").GetBoolean()||!before.GetProperty("verified").GetBoolean()
28 ||current.GetProperty("count").GetInt32()!=before.GetProperty("count").GetInt32()
29 ||current.GetProperty("credits").GetInt64()!=before.GetProperty("credits").GetInt64())continue;
30 await using var file=new FileStream(confirmed,FileMode.CreateNew,FileAccess.Write,FileShare.Read);
31 await JsonSerializer.SerializeAsync(file,new{operationKey=key,submitted=false,reconciledAt=DateTimeOffset.UtcNow,channel=channel.Identity,
32 pendingSha256=Convert.ToHexStringLower(SHA256.HashData(bytes)),originalOperationStatus=status,actualClientInventory=current},cancellationToken:token);
33 }
34 }
35 }
Modified XFEEDToolBox.Core/Session/SessionMaintenanceExit.cs +5 -0
@@ -3,6 +3,11 @@ namespace XFEEDToolBox.Core.Session;
3 3 /// <summary>An update may finish a client only after its original world session has ended.</summary>
4 4 public static class SessionMaintenanceExit
5 5 {
6 public static async Task ReleaseAfterExitAsync(Func<Task> release,Func<bool> confirmedMenuExit)
7 {
8 try{await release().ConfigureAwait(false);}
9 catch(Exception error)when(confirmedMenuExit()&&error is IOException or InvalidDataException or OperationCanceledException){}
10 }
6 11 public static void RequireMainMenu(NativeSessionFrame frame,DateTimeOffset now)
7 12 {
8 13 var age=now-frame.ObservedAt;
Modified XFEEDToolBox.Test/NativeTradeCommandDriverTests.cs +8 -2
@@ -18,7 +18,7 @@ public class NativeTradeCommandDriverTests
18 18 public ulong ActualMarket=1;public Action? OnReadinessProbe;
19 19 public long RepairNeeded,IntegrityNeeded,RearmNeeded;public int IntegrityWear;public bool KeepServiceOutstanding;
20 20 public bool QuoteSnapshotsSupported=true,FailPostTradeReadOnce;private bool currentQuote;private ulong quotedGeneration;private readonly HashSet<string> consumedServices=[];
21 public bool ProfileRefreshSupported=true,MarketHasCredits=true,MissingServerCargo;public long ServerCreditsOffset;public int ProfileRefreshes,ServerCargoOffset;
21 public bool ProfileRefreshSupported=true,MarketWalletOptional=true,MarketHasCredits=true,MissingServerCargo;public long ServerCreditsOffset;public int ProfileRefreshes,ServerCargoOffset;
22 22 public string Commodity="biowaste";public uint CommodityId=128049244;public int UnitBuy=68,UnitSell=80;public bool BatchSupported;
23 23 public bool Goals;public long Contribution;public int CgReads;
24 24 private ulong generation;private int pending;
@@ -27,7 +27,7 @@ public class NativeTradeCommandDriverTests
27 27 public async Task<JsonElement> CallAsync(object request,CancellationToken token)
28 28 {
29 29 var command=Json(request);var op=command.GetProperty("op").GetString();
30 if(op=="describe")return Json(new{schema=1,name="XFEEDToolBox.Navigation",verified=true,gameSha256=NativeSystemLocationReader.GameSha256,commerceDockedReadiness=true,cgCommodityBatches=BatchSupported,formalCommodityTrading=BatchSupported,serviceQuoteSnapshots=QuoteSnapshotsSupported,commerceClientProfileRefresh=ProfileRefreshSupported});
30 if(op=="describe")return Json(new{schema=1,name="XFEEDToolBox.Navigation",verified=true,gameSha256=NativeSystemLocationReader.GameSha256,commerceDockedReadiness=true,cgCommodityBatches=BatchSupported,formalCommodityTrading=BatchSupported,serviceQuoteSnapshots=QuoteSnapshotsSupported,commerceClientProfileRefresh=ProfileRefreshSupported,marketWalletOptional=MarketWalletOptional});
31 31 if(op is "cg.read" or "cg.read.mine")
32 32 {
33 33 if(!Goals||command.GetProperty("marketId").GetInt64()!=99)throw new InvalidOperationException("CG was queried outside the configured destination");
@@ -102,6 +102,12 @@ public class NativeTradeCommandDriverTests
102 102 driver.WalletObserved+=observation=>channel.Player=observation.Project(channel.Player);return driver;
103 103 }
104 104 private static TradeAction Buy()=>new(TradeActionKind.Buy,new(){From=new(){MarketId=1},To=new(){MarketId=2},Orders=[new("biowaste","Biowaste",1,68,80)]},new("biowaste","Biowaste",1,68,80));
105 [Test] public async Task TheKnownUnsupportedMarketSchemaIsRejectedBeforeCreatingAnyOrder()
106 {
107 using var directory=new TemporaryDirectory();var channel=new Channel{BatchSupported=true,MarketWalletOptional=false};var driver=Driver(channel,directory.Path,new(16,100));var refused=false;
108 try{await driver.PreflightAsync(default);}catch(NativeTradeSdkUpgradeRequiredException){refused=true;}
109 Check.That(refused);Check.Equal(0,channel.Mutations);Check.Equal(0,channel.MarketReads);Check.Equal(0,Directory.GetFiles(directory.Path,"*.pending.json").Length);
110 }
105 111 [Test] public async Task SourceQuoteCrossChecksTheActualClientWithoutInventingAProfile()
106 112 {
107 113 using var directory=new TemporaryDirectory();var channel=new Channel{MarketHasCredits=false};var driver=Driver(channel,directory.Path);
Added XFEEDToolBox.Test/NativeUnsubmittedTradeIntentsTests.cs +60 -0
@@ -0,0 +1,60 @@
1 using System.Text.Json;
2 using XFEExtension.NetCore.XUnit.Attributes;
3 using XFEEDToolBox.Core.Execution;
4 using XFEEDToolBox.Core.Models;
5
6 namespace XFEEDToolBox.Test;
7
8 [TestFixture]
9 public class NativeUnsubmittedTradeIntentsTests
10 {
11 private sealed class Channel:IOriginalCommerceChannel
12 {
13 public string Identity=>"100:200";
14 public bool Known;
15 public int Calls;
16 public long Credits=10000;
17 public Task<JsonElement> CallAsync(object request,CancellationToken token)
18 {
19 Calls++;var op=JsonSerializer.SerializeToElement(request).GetProperty("op").GetString();
20 return Task.FromResult(op switch{
21 "commerce.operation.status"=>JsonSerializer.SerializeToElement(new{known=Known,mutationsSent=Known?1:0}),
22 "commerce.inventory"=>JsonSerializer.SerializeToElement(new{verified=true,count=0,credits=Credits}),
23 _=>throw new InvalidOperationException("Only read-only reconciliation is allowed")});
24 }
25 }
26 private static PlayerState Player()=>new(){InGame=true,Docked=true,CommanderId="test-commander",CurrentShipId=7,
27 LoadGameAt=DateTimeOffset.UtcNow.AddMinutes(-1),Credits=10000,CreditsReliable=true,CargoReliable=true};
28 private static string Pending(string directory,Channel channel,PlayerState player)
29 {
30 var file=Path.Combine(directory,new string('a',32)+".pending.json");
31 File.WriteAllText(file,JsonSerializer.Serialize(new{operationKey=new string('a',32),channel=channel.Identity,player.CommanderId,player.CurrentShipId,player.LoadGameAt,
32 intent=new{before=new{verified=true,count=0,credits=10000}}}));return file;
33 }
34 [Test] public async Task SameLiveSessionUnacceptedKeyIsMarkedUnsubmittedWithoutDeletingTheIntent()
35 {
36 using var directory=new TemporaryDirectory();var channel=new Channel();var player=Player();var pending=Pending(directory.Path,channel,player);var original=File.ReadAllText(pending);
37 await NativeUnsubmittedTradeIntents.ReconcileAsync(directory.Path,channel,player,default);
38 using var proof=JsonDocument.Parse(File.ReadAllText(pending.Replace(".pending.json",".confirmed.json")));
39 Check.That(!proof.RootElement.GetProperty("submitted").GetBoolean());Check.That(!proof.RootElement.TryGetProperty("receipt",out _));
40 Check.Equal(original,File.ReadAllText(pending));Check.Equal(2,channel.Calls);
41 }
42 [Test] public async Task NewSessionCannotUseTheOldOperationMapAsProof()
43 {
44 using var directory=new TemporaryDirectory();var channel=new Channel();var player=Player();Pending(directory.Path,channel,player);
45 await NativeUnsubmittedTradeIntents.ReconcileAsync(directory.Path,channel,player with{LoadGameAt=DateTimeOffset.UtcNow},default);
46 Check.Equal(0,channel.Calls);Check.Equal(0,Directory.GetFiles(directory.Path,"*.confirmed.json").Length);
47 }
48 [Test] public async Task AcceptedKeyRemainsUnresolved()
49 {
50 using var directory=new TemporaryDirectory();var channel=new Channel{Known=true};var player=Player();Pending(directory.Path,channel,player);
51 await NativeUnsubmittedTradeIntents.ReconcileAsync(directory.Path,channel,player,default);
52 Check.Equal(1,channel.Calls);Check.Equal(0,Directory.GetFiles(directory.Path,"*.confirmed.json").Length);
53 }
54 [Test] public async Task ChangedWalletCannotBeUsedAsUnsubmittedProof()
55 {
56 using var directory=new TemporaryDirectory();var channel=new Channel{Credits=9999};var player=Player();Pending(directory.Path,channel,player);
57 await NativeUnsubmittedTradeIntents.ReconcileAsync(directory.Path,channel,player,default);
58 Check.Equal(0,Directory.GetFiles(directory.Path,"*.confirmed.json").Length);
59 }
60 }
Modified XFEEDToolBox.Test/SessionMaintenanceExitTests.cs +8 -0
@@ -6,6 +6,14 @@ namespace XFEEDToolBox.Test;
6 6 [TestFixture]
7 7 public class SessionMaintenanceExitTests
8 8 {
9 [Test] public async Task AClosedPipeIsHarmlessOnlyAfterConfirmedMenuExit()
10 {
11 await SessionMaintenanceExit.ReleaseAfterExitAsync(()=>throw new InvalidDataException("Pipe closed with process"),()=>true);
12 var refused=false;
13 try{await SessionMaintenanceExit.ReleaseAfterExitAsync(()=>throw new InvalidDataException("Pipe closed before exit"),()=>false);}
14 catch(InvalidDataException){refused=true;}
15 Check.That(refused);
16 }
9 17 [Test] public void OnlyFreshStableOriginalMainMenuPermitsMaintenanceExit()
10 18 {
11 19 var now=DateTimeOffset.UtcNow;var frame=new NativeSessionFrame(1,now,"MainMenu","MainMenu",[]);
Modified XFEEDToolBox/Services/WindowsTradingBootstrap.cs +6 -3
@@ -7,7 +7,7 @@ using XFEEDToolBox.Core.Session;
7 7
8 8 namespace XFEEDToolBox.Services;
9 9
10 public sealed class WindowsTradingBootstrap(Func<PlayerState> player,string executable,string packageDirectory)
10 public sealed class WindowsTradingBootstrap(Func<PlayerState> player,string executable,string packageDirectory,string? operationDirectory=null)
11 11 {
12 12 public event Action<string>? Progress;
13 13 public async Task UpgradeAndEnterAsync(CancellationToken token)
@@ -39,12 +39,14 @@ public sealed class WindowsTradingBootstrap(Func<PlayerState> player,string exec
39 39 {
40 40 if(original.InGame&&(!original.Docked||!original.CargoReliable||original.CargoCount!=0||original.CurrentShipId is null))
41 41 throw new InvalidOperationException("更新前需要确认停靠和空货舱;当前游戏已保留。");
42 if(operationDirectory is not null)
43 await NativeUnsubmittedTradeIntents.ReconcileAsync(operationDirectory,new NativeCommerceChannel(target.ProcessId),original,token).ConfigureAwait(false);
42 44 using var game=Process.GetProcessById(target.ProcessId);
43 45 if(game.StartTime.ToUniversalTime().Ticks!=target.StartedUtcTicks||!string.Equals(game.MainModule?.FileName,target.Executable,StringComparison.OrdinalIgnoreCase))
44 46 throw new InvalidOperationException("准备更新的游戏实例已改变。");
45 47 Progress?.Invoke("正在通过游戏原始菜单退出当前会话以更新插件");
46 48 var recovery=new NativeSessionRecoveryChannel(target.ProcessId,NativeRelogChannel.SupportedGameSha256,Path.Combine(packageDirectory,"DockingControl"));
47 var owner=Guid.NewGuid().ToString("N");
49 var owner=Guid.NewGuid().ToString("N");var endedAtMenu=false;
48 50 recovery.Progress+=text=>Progress?.Invoke(text);
49 51 try
50 52 {
@@ -53,8 +55,9 @@ public sealed class WindowsTradingBootstrap(Func<PlayerState> player,string exec
53 55 SessionMaintenanceExit.RequireMainMenu(frame,DateTimeOffset.UtcNow);
54 56 Progress?.Invoke("已确认游戏主菜单,正在结束客户端以加载新版插件");
55 57 await lifecycle.TerminateAsync(target,token).ConfigureAwait(false);
58 endedAtMenu=true;
56 59 }
57 finally{await recovery.EndAsync(owner).ConfigureAwait(false);}
60 finally{await SessionMaintenanceExit.ReleaseAfterExitAsync(()=>recovery.EndAsync(owner),()=>endedAtMenu&&game.HasExited).ConfigureAwait(false);}
58 61 using var menuDeadline=CancellationTokenSource.CreateLinkedTokenSource(token);menuDeadline.CancelAfter(TimeSpan.FromSeconds(15));
59 62 await game.WaitForExitAsync(menuDeadline.Token).ConfigureAwait(false);
60 63 }
Modified XFEEDToolBox/ViewModels/AutomaticTradeViewModel.cs +1 -1
@@ -77,7 +77,7 @@ public partial class ToolboxViewModel
77 77 using var stop=CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);automaticTradeStop=stop;RunActive=true;HasError=false;
78 78 try
79 79 {
80 var executable=PluginGameExecutable;var bootstrap=new WindowsTradingBootstrap(()=>runtime.Player,executable,Path.Combine(AppContext.BaseDirectory,"PluginPackage"));
80 var executable=PluginGameExecutable;var bootstrap=new WindowsTradingBootstrap(()=>runtime.Player,executable,Path.Combine(AppContext.BaseDirectory,"PluginPackage"),Path.Combine(value.WorkingDirectory,"operations"));
81 81 bootstrap.Progress+=message=>dispatcher.TryEnqueue(()=>{RunStatus="更新并恢复";RunMessage=message;runtime.Log("跑商更新",message);});
82 82 await Task.Run(()=>bootstrap.UpgradeAndEnterAsync(stop.Token),stop.Token);succeeded=true;AutomaticPluginUpdateRequired=false;
83 83 }
Modified docs/TRADE-WORK-COORDINATION.md +9 -0
@@ -2,6 +2,15 @@
2 2
3 3 更新:2026-10-25(Asia/Shanghai)。最新状态以紧接下方的记录为准,后文保留历史故障及验收过程。
4 4
5 ## 0.5.17已实际买入362t铀,程序正自动运输(2026-10-25 06:27)
6
7 - 唯一工具箱98656/r8,实际游戏97564。用户已授权的更新由工具箱在Polyakov停靠空舱后完成;原始LoadGame为06:24:52、06:25:44 Location确认原Solo/Type-9/7/752t,游戏加载器SHA-256 414981dabc0a81b448d1b590c4260180f2dfdc78480f124ee610c08201e0e2e7,对应0.5.17-dev;游戏构建与ABI未变。没有因通用危险标记停航。
8 - 旧0.5.16采购入口也错误要求行情含credits,06:15:24在入队前直接拒绝f6115bfbb6f64b02879388982aaf5d5d。更新前工具箱使用同一原进程/会话的操作键映射确认known=false、mutationsSent=0,且实际库存和钱包与意图提交前一致;另存submitted=false与原pending哈希,保留原意图,不伪造成功交易。跨进程/跨LoadGame、已接受键或余额不符均不能这样核对,4项回归通过。
9 - 新原生入口按真实行情协议将缺失钱包字段视为未提供;字段若存在仍严格检查数值与实际钱包一致。采购仍核对新鲜船舶、实际钱包/货舱、原SKU、合法性、库存、价格、资金与费用预留;成交后服务器金额和原游戏库存/钱包回调必须全部成功。正式批次的键容量与原CG批次一致为4096,不再误用旧1t验收的32个键限制,不丢弃已接受键。原26导出/ABI1和33次相关原生隔离检查通过,29项驱动回归通过。
10 - 06:26:23采购3ac1b6197f6344229fecd2084e874b73真实确认:362t Uranium、7241Cr/t,总成本2,621,242Cr;钱包140,340,795→137,719,553,货舱0→362,原生state3/error0、serverConfirmed=true/clientApplied=true、mutationsSent=1。当前旅程继续原来按当次可用库存规划的362t订单,752t是实际货舱上限。不得重买同批。卖出、CG新增贡献与本批净收益仍待真实确认,不能提前计入利润。
11 - 当前历史工作目录净28,717,654Cr,已包含此前Mawson服务10Cr和本次Polyakov服务1437Cr;新批次尚未实现利润。旧192t失败采购及人工完成证据继续分别保留。新界面将历史累计与本次启动新增收益分开,运行中取消按钮经后台原图、局部、OCR/UIA核验可见启用,没有为视觉验证点击取消。
12 - 正常主菜单退出后的管道释放可能因客户端已经结束返回空消息;现在只在原主菜单退出已确认且该进程确实结束时忽略通信清理错误,其他情况仍抛出,2项菜单退出回归通过。Release构建0警告0错误。标准插件构建现同时生成/打包CruiseControl,扩展二进制与私有运行文件不提交。没有定时任务、子智能体、键鼠或助手驾驶/交易指令,持续执行由工具箱自己的任务持有。
13
5 14 ## Homer真实停靠、CG与行情核对后自动续往Polyakov(2026-10-25 06:09)
6 15
7 16 - 06:03:37真实Docked确认Homer/4210924803。接管和停靠均由工具箱程序完成,助手没有驾驶;随后CG读取比原生停靠状态早一帧,被原接口拒绝。现在仅对入队前的这一已知拒绝等待最多10秒,已接受的CG代次只轮询同一代次;报名意图不重放。3项新增回归通过,真实原始个人CG响应确认864仍有效/已报名,贡献1152。
Modified native/ManagedPlugin/Navigation.CommerceTrade.cs +2 -2
@@ -104,11 +104,11 @@ internal static unsafe partial class Navigation
104 104 return Obj(("generation", previous), ("duplicate", true));
105 105 }
106 106 if (commerceReconciliationRequired) throw new InvalidOperationException("An uncertain order requires a fresh game session to reconcile inventory and credits; no order was retried");
107 if (commerceOperationKeys.Count >= (batch?4096:32) || commerceRead.state != 3 || commerceRead.kind!=0 || commerceRead.market != market || commerceRead.entity != frame.entity || commerceRead.life != frame.life || GetTickCount64() - commerceRead.observed > 60000) throw new InvalidOperationException("Read the current original market and cargo before sending an order");
107 if (commerceOperationKeys.Count >= CommerceKeyCapacity(formal,batch) || commerceRead.state != 3 || commerceRead.kind!=0 || commerceRead.market != market || commerceRead.entity != frame.entity || commerceRead.life != frame.life || GetTickCount64() - commerceRead.observed > 60000) throw new InvalidOperationException("Read the current original market and cargo before sending an order");
108 108 using var document = JsonDocument.Parse(commerceReadBody); var response = document.RootElement;
109 109 var quote = response.Required("commodities").Required(commodity.ToString(System.Globalization.CultureInfo.InvariantCulture));
110 110 var observed = ReadCommerceShipInventory(frame); if (!observed.verified) throw new InvalidOperationException("Actual original wallet and cargo are unavailable");
111 if(!response.TryGetProperty("credits",out var serverBalance)||!serverBalance.TryGetUInt64(out var serverCredits)||serverCredits!=observed.credits)
111 if(!QuotedWalletMatches(response,observed.credits))
112 112 throw new InvalidOperationException("Original server wallet differs from the actual client; refresh the original profile before submitting an order");
113 113 var price = quote.Required(delta > 0 ? "buyPrice" : "sellPrice").GetUInt32(); var before = CommerceInventoryCount(response, commodity);
114 114 var total = 0;
Modified native/ManagedPlugin/Navigation.FormalCommerce.cs +11 -0
@@ -5,6 +5,11 @@ namespace XFEEDToolBox.Plugin;
5 5
6 6 internal static unsafe partial class Navigation
7 7 {
8 private static int CommerceKeyCapacity(bool formal,bool batch)=>formal||batch?4096:32;
9 private static bool QuotedWalletMatches(JsonElement response,ulong actual)
10 =>!response.TryGetProperty("credits",out var value)||value.ValueKind==JsonValueKind.Number&&value.TryGetUInt64(out var quoted)&&quoted==actual;
11 private static bool QuotedWalletFixture(string body,ulong actual,bool expected)
12 {using var value=JsonDocument.Parse(body);return QuotedWalletMatches(value.RootElement,actual)==expected;}
8 13 private static bool FormalCommodityName(string name) => name.Length is >0 and <128
9 14 && name.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-');
10 15 private static string CommerceExpectedCommodity(in CommerceReadRequest work)
@@ -23,6 +28,12 @@ internal static unsafe partial class Navigation
23 28 }
24 29 private static bool FormalCommerceFixture()
25 30 {
31 if(CommerceKeyCapacity(true,false)!=4096||CommerceKeyCapacity(false,true)!=4096||CommerceKeyCapacity(false,false)!=32)return false;
32 if(!QuotedWalletFixture("{\"inventory\":[]}",100000000,true)
33 ||!QuotedWalletFixture("{\"credits\":100000000}",100000000,true)
34 ||!QuotedWalletFixture("{\"credits\":99999999}",100000000,false)
35 ||!QuotedWalletFixture("{\"credits\":null}",100000000,false)
36 ||!QuotedWalletFixture("{\"credits\":\"100000000\"}",100000000,false))return false;
26 37 var work=new CommerceReadRequest{formal=true,capacityBound=752,kind=1,commodity=123456,delta=752,before=0,after=752,totalBefore=0,creditsBefore=100000000,price=7241};
27 38 SetCommerceCommodity(ref work,"gold");
28 39 if(!CommerceExpectedCredits(work,out var expected)||expected!=94554768||CommerceExpectedCommodity(work)!="gold")return false;
Modified native/ManagedPlugin/Navigation.Protocol.cs +1 -1
Modified native/ManagedPlugin/Platform.cs +1 -1
Modified scripts/Build-Plugin.ps1 +1 -0