using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed partial class NemesisApi(ItemCatalog catalog, TimeProvider clock)
{
public static readonly HashSet<string> Controllers = ["nemesisController"];
private static readonly string[] Words = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"];
private static string SymbolMod(int symbol, bool antivirus) => symbol is >= 0 and <= 7 ? "/Lotus/Upgrades/Mods/Immortal/" + (antivirus ? "Antivirus" : "Immortal") + Words[symbol] + "Mod" : !antivirus && symbol == 9 ? "/Lotus/Upgrades/Mods/Immortal/ImmortalWildcardMod" : throw new ApiException(400, "Invalid requiem symbol");
public ApiResponse Handle(JObject account, ApiRequest request)
{
var body = request.ObjectBody(); var inv = account.Obj("Inventory"); var mode = request.Q("mode");
if (mode == "s") return Start(account, body);
if (mode == "f") return Fusion(inv, body);
if (mode == "t") { inv["LastNemesisAllySpawnTime"] = Wire.Date(clock.GetUtcNow().ToUnixTimeSeconds() * 1000); return ApiResponse.Json(new JObject { ["NewTime"] = inv["LastNemesisAllySpawnTime"]!.DeepClone() }); }
if (mode == "d")
{
var fps = body["nemesisFingerprints"] as JArray ?? throw new ApiException(400, "Missing nemesis fingerprints"); if (fps.Count > 1000) throw new ApiException(400, "Too many nemeses");
foreach (var fp in fps.Select(NemesisData.Fingerprint).Distinct()) foreach (var entry in inv.Array("NemesisHistory").OfType<JObject>().Where(x => NemesisData.Fingerprint(x["fp"]) == fp).ToArray()) entry.Remove();
return ApiResponse.Json(body);
}
var nemesis = inv["Nemesis"] as JObject ?? throw new ApiException(404, "No active nemesis");
if (mode == "rs") { nemesis["LastEnc"] = nemesis.Value<int>("MissionCount"); return ApiResponse.Json(new { LastEnc = nemesis.Value<int>("LastEnc") }); }
if (mode == "w") return ApiResponse.Json(new JObject { ["target"] = NemesisData.ForGame(nemesis) });
if (mode == "p")
{
var maxSymbol = nemesis.Value<string>("Faction") == "FC_INFESTATION" ? 15 : 9;
if (body["guess"] is not JArray { Count: 3 } guess || guess.Any(x => x.Type != JTokenType.Integer || x.Value<int>() < 0 || x.Value<int>() > maxSymbol)) throw new ApiException(400, "Invalid requiem sequence");
var code = NemesisData.Passcode(nemesis); var result = code.Length == 1 ? Array.IndexOf(guess.Values<int>().ToArray(), code[0]) + 1 : Enumerable.Range(0, 3).Count(i => guess[i].Value<int>() == code[i] || guess[i].Value<int>() == 9);
return ApiResponse.Json(new { GuessResult = result });
}
if (mode == "r") return Requiem(account, nemesis, body);
throw new ApiException(400, "Unknown nemesis operation");
}
private ApiResponse Start(JObject account, JObject body)
{
var inv = account.Obj("Inventory"); var target = body["target"] as JObject ?? throw new ApiException(400, "Missing nemesis target"); var type = target.RequiredString("manifest"); var manifest = NemesisData.Manifest(type);
var fp = NemesisData.Fingerprint(target["fp"] ?? new JValue(0)); if (fp == 0) fp = Wire.Seed();
if (inv["Nemesis"] is JObject current)
{
if (NemesisData.Fingerprint(current["fp"]) == fp && current.Value<string>("manifest") == type) return ApiResponse.Json(new JObject { ["target"] = NemesisData.ForGame(current) });
throw new ApiException(409, "Resolve the current nemesis first");
}
var faction = type.Contains("/Lawyers/", StringComparison.Ordinal) ? "FC_CORPUS" : type.Contains("/InfestedLich/", StringComparison.Ordinal) ? "FC_INFESTATION" : "FC_GRINEER";
if (target["Faction"] is not null && target.Value<string>("Faction") != faction) throw new ApiException(400, "Nemesis faction does not match manifest");
var suit = target.RequiredString("KillingSuit"); if (GameData.Find("Warframes", suit)?["nemesisUpgradeTag"] is null || !inv.Array("Suits").Any(x => x.Value<string>("ItemType") == suit)) throw new ApiException(400, "Progenitor Warframe is not owned");
var weapons = manifest["weapons"]!.Values<string>().ToArray(); var index = -1;
if (weapons.Length > 0)
{
index = new SeededRng(fp).Int(0, weapons.Length - 1); var start = index; var disallowed = (target["DisallowedWeapons"] as JArray ?? []).Values<string>().ToHashSet();
while (disallowed.Contains(weapons[index])) { index = (index + 1) % weapons.Length; if (index == start) throw new ApiException(400, "All nemesis weapons are excluded"); }
}
if (inv.Value<bool>("noNemesis")) return ApiResponse.Json(new JObject());
var created = NemesisData.FromTrade(new JObject { ["fp"] = fp, ["manifest"] = type, ["KillingSuit"] = suit, ["killingDamageType"] = target.Integer("killingDamageType", 0, 32), ["ShoulderHelmet"] = string.IsNullOrEmpty(target.Value<string>("ShoulderHelmet")) ? NemesisData.Helmet(suit) : target.RequiredString("ShoulderHelmet"), ["WeaponIdx"] = index, ["AgentIdx"] = target.Integer("AgentIdx", 0, 100), ["BirthNode"] = target.RequiredString("BirthNode"), ["Faction"] = faction, ["d"] = Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds()) });
created["Traded"] = false; created["PrevOwners"] = 0; inv["Nemesis"] = created; account.Remove("NemesisRequiemReceipt"); return ApiResponse.Json(new JObject { ["target"] = NemesisData.ForGame(created) });
}
private static ApiResponse Fusion(JObject inv, JObject body)
{
var category = body.RequiredString("Category"); if (category is not ("LongGuns" or "Pistols" or "Melee" or "SpaceGuns")) throw new ApiException(400, "Invalid valence fusion category");
var destId = Wire.Id(body["DestWeapon"]); var sourceId = Wire.Id(body["SourceWeapon"]); if (destId == sourceId) throw new ApiException(400, "Cannot fuse a weapon with itself");
var dest = Inventory.Equipment(inv, category, destId); var source = Inventory.Equipment(inv, category, sourceId); Inventory.RequireNotInResearch(inv, sourceId);
if (dest.Value<string>("ItemType") != source.Value<string>("ItemType") || dest.Value<string>("UpgradeType") != "/Lotus/Weapons/Grineer/KuvaLich/Upgrades/InnateDamageRandomMod" || source.Value<string>("UpgradeType") != dest.Value<string>("UpgradeType")) throw new ApiException(400, "Weapons do not support this fusion");
var first = JObject.Parse(dest.RequiredString("UpgradeFingerprint")); var second = JObject.Parse(source.RequiredString("UpgradeFingerprint"));
if (first["buffs"] is not JArray { Count: 1 } firstBuff || second["buffs"] is not JArray { Count: 1 } secondBuff) throw new ApiException(400, "Invalid innate weapon bonus");
var a = ((JObject)firstBuff[0]).Integer("Value", 0, 0x40000000); var b = ((JObject)secondBuff[0]).Integer("Value", 0, 0x40000000);
var damage = Math.Max(.25 + a / (double)0x3fffffff * .35, .25 + b / (double)0x3fffffff * .35) * 1.1; if (damage >= .5794998) damage = .6;
if (body.Value<bool>("UseSourceDmgType")) firstBuff[0]["Tag"] = secondBuff[0]["Tag"]!.DeepClone(); firstBuff[0]["Value"] = (long)((damage - .25) / .35 * 0x3fffffff); dest["UpgradeFingerprint"] = first.ToString(Formatting.None);
source.Remove(); Inventory.FreeSlot(inv, category);
return ApiResponse.Json(new JObject { ["InventoryChanges"] = new JObject { [category] = new JArray(dest.DeepClone()), ["RemovedIdItems"] = new JArray(new JObject { ["ItemId"] = Wire.Oid(sourceId) }), [Inventory.SlotFor(category)!] = new JObject { ["Slots"] = 1 } } });
}
private static JArray KnifeConfig(JObject account)
{
// CurrentLoadOutIds uses the game's enum: DATAKNIFE = 7, MECH = 8.
var inv = account.Obj("Inventory"); var id = (inv["CurrentLoadOutIds"] as JArray)?.ElementAtOrDefault(7); var presets = account.Obj("Loadouts").Array("DATAKNIFE"); var preset = presets.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == Wire.Id(id)) ?? presets.OfType<JObject>().FirstOrDefault();
var knifeId = Wire.Id(preset?["s"]?["ItemId"] ?? preset?["s"]?["itemId"]); var knife = inv.Array("DataKnives").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == knifeId) ?? inv.Array("DataKnives").OfType<JObject>().FirstOrDefault() ?? throw new ApiException(400, "No Parazon equipped");
var config = preset?["s"]?.Value<int>("mod") ?? 0; return (knife["Configs"] as JArray)?.ElementAtOrDefault(config)?["Upgrades"] as JArray ?? throw new ApiException(400, "No Parazon mods equipped");
}
private static JObject ResolveMod(JObject inv, string reference)
{
var mod = inv.Array("Upgrades").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == reference);
if (mod is not null) { var type = mod.Value<string>("ItemType") ?? ""; if ((type.Contains("/Immortal/", StringComparison.Ordinal) || type.Contains("/Potency/", StringComparison.Ordinal)) && JObject.Parse(mod.Value<string>("UpgradeFingerprint") ?? "{}").Value<int>("lvl") >= (GameData.Find("Upgrades", type)?.Value<int?>("fusionLimit") ?? 3)) throw new ApiException(409, "Parazon mod has no charges remaining"); return mod; }
if (!inv.Array("RawUpgrades").Any(x => x.Value<string>("ItemType") == reference && x.Value<long>("ItemCount") > 0)) throw new ApiException(400, "Equipped Parazon mod is not owned");
return new JObject { ["ItemType"] = reference };
}
private static void Charge(JObject inv, JArray config, JObject mod, JObject response)
{
var type = mod.RequiredString("ItemType"); var id = Wire.Id(mod["ItemId"]); var created = id.Length == 0;
if (created)
{
Inventory.AddCount(inv, "RawUpgrades", type, -1); id = Wire.NewId(); mod = new JObject { ["ItemId"] = Wire.Oid(id), ["ItemType"] = type, ["UpgradeFingerprint"] = "{\"lvl\":1}" }; inv.Array("Upgrades").Add(mod);
var index = config.Select(x => x.ToString()).ToList().IndexOf(type); if (index < 0) throw new ApiException(400, "Mod is not equipped"); config[index] = id;
}
else { var fingerprint = JObject.Parse(mod.Value<string>("UpgradeFingerprint") ?? "{}"); fingerprint["lvl"] = fingerprint.Value<int>("lvl") + 1; mod["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None); }
response["HasKnife"] = true; response.Array("UpgradeIds").Add(id); response.Array("UpgradeTypes").Add(type); response.Array("UpgradeFingerprints").Add(JObject.Parse(mod.Value<string>("UpgradeFingerprint")!)); response.Array("UpgradeNew").Add(created);
}
private static void Weaken(JObject nemesis) { nemesis["Weakened"] = true; nemesis["InfNodes"] = new JArray(new JObject { ["Node"] = NemesisData.Manifest(nemesis.RequiredString("manifest"))["showdownNode"]!.DeepClone(), ["Influence"] = 1 }); }
private static int AntivirusGain(string? type) => type switch
{
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusAndSpeedOnUseMod" or
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusAndWeaponDamageOnUseMod" or
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusSmallOnSingleUseMod" => 10,
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusLargeOnSingleUseMod" or
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusOnUseMod" => 15,
_ => 0
};
private ApiResponse Requiem(JObject account, JObject nemesis, JObject body)
{
var inv = account.Obj("Inventory"); var key = nemesis["fp"] + ":" + nemesis.Value<int>("MissionCount") + ":" + body.ToString(Formatting.None);
if (account["NemesisRequiemReceipt"] is JObject receipt && receipt.Value<string>("key") == key) return ApiResponse.Json(receipt["response"]);
if (nemesis.Value<bool>("Weakened")) throw new ApiException(409, "Nemesis is already weakened");
var guess = (int)body.Integer("guess", 0, 4095); var position = (int)body.Integer("position", 0, 2); var config = KnifeConfig(account); var response = new JObject(); var code = NemesisData.Passcode(nemesis);
if (code.Length == 1)
{
int[] symbols = [guess & 15, guess >> 4 & 15, guess >> 8 & 15]; var results = symbols.Select(x => x == code[0] ? 2 : 1).ToArray();
// Coda attachment/guess enumeration can differ from physical slot order.
// Validate ownership against the active config, never the client-supplied knife.
// Potency shares the three bottom slots with antivirus, not the utility slots.
var mods = config.Skip(3).Take(3).Where(x => x.Type == JTokenType.String && x.ToString().Length > 0)
.Select(x => ResolveMod(inv, x.ToString())).ToArray();
var available = mods.GroupBy(x => x.RequiredString("ItemType")).ToDictionary(x => x.Key, x => x.Count());
foreach (var symbol in symbols.Where(x => x < 8))
{
var type = SymbolMod(symbol, true);
if (!available.TryGetValue(type, out var count) || count == 0) throw new ApiException(400, "Antivirus sequence does not match equipped mods");
available[type] = count - 1;
}
nemesis.Array("GuessHistory").Add(NemesisData.Encode(symbols, results));
if (results.Contains(2))
{
var gain = 5; foreach (var mod in mods)
{
var extra = AntivirusGain(mod.Value<string>("ItemType"));
if (extra > 0) { gain += extra; Charge(inv, config, mod, response); }
}
nemesis["HenchmenKilled"] = Math.Min(100, nemesis.Value<double>("HenchmenKilled") + gain * (inv.Value<double?>("nemesisAntivirusGainMultiplier") ?? 1));
if (nemesis.Value<double>("HenchmenKilled") >= 100)
{
var antivirus = mods.First(x => x.Value<string>("ItemType") == SymbolMod(code[0], true));
Charge(inv, config, antivirus, response); Weaken(nemesis);
}
}
if (!nemesis.Value<bool>("Weakened")) nemesis["InfNodes"] = NemesisData.Nodes(nemesis.RequiredString("manifest"), 0);
}
else
{
if (config.Count <= 3 + position || ResolveMod(inv, config[3 + position].ToString()).Value<string>("ItemType") != SymbolMod(guess, false)) throw new ApiException(400, "Requiem does not match equipped mod");
var history = nemesis.Array("GuessHistory"); if (position == 0) history.Add(NemesisData.Encode([8, 8, 8], [0, 0, 0])); if (history.Count == 0) throw new ApiException(409, "Start with the first requiem");
var (symbols, results) = NemesisData.Decode(history.Last!.Value<int>()); if (Enumerable.Range(0, position).Any(i => results[i] != 2) || results[position] != 0) throw new ApiException(409, "Requiem sequence is out of order");
var correct = guess == 9 || guess == code[position]; symbols[position] = guess; results[position] = correct ? 2 : 1; history[history.Count - 1] = NemesisData.Encode(symbols, results);
if (!correct) { response["RankIncrease"] = 1; nemesis["Rank"] = Math.Min(nemesis.Value<int>("Rank") + 1, NemesisData.Systems(nemesis.RequiredString("manifest")).Length - 1); nemesis["InfNodes"] = NemesisData.Nodes(nemesis.RequiredString("manifest"), nemesis.Value<int>("Rank")); }
else if (position == 2) { for (var i = 3; i < 6; i++) Charge(inv, config, ResolveMod(inv, config[i].ToString()), response); Weaken(nemesis); }
}
account["NemesisRequiemReceipt"] = new JObject { ["key"] = key, ["response"] = response.DeepClone() }; return ApiResponse.Json(response);
}
}
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed partial class NemesisApi(ItemCatalog catalog, TimeProvider clock)
{
public static readonly HashSet<string> Controllers = ["nemesisController"];
private static readonly string[] Words = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"];
private static string SymbolMod(int symbol, bool antivirus) => symbol is >= 0 and <= 7 ? "/Lotus/Upgrades/Mods/Immortal/" + (antivirus ? "Antivirus" : "Immortal") + Words[symbol] + "Mod" : !antivirus && symbol == 9 ? "/Lotus/Upgrades/Mods/Immortal/ImmortalWildcardMod" : throw new ApiException(400, "Invalid requiem symbol");
public ApiResponse Handle(JObject account, ApiRequest request)
{
var body = request.ObjectBody(); var inv = account.Obj("Inventory"); var mode = request.Q("mode");
if (mode == "s") return Start(account, body);
if (mode == "f") return Fusion(inv, body);
if (mode == "t") { inv["LastNemesisAllySpawnTime"] = Wire.Date(clock.GetUtcNow().ToUnixTimeSeconds() * 1000); return ApiResponse.Json(new JObject { ["NewTime"] = inv["LastNemesisAllySpawnTime"]!.DeepClone() }); }
if (mode == "d")
{
var fps = body["nemesisFingerprints"] as JArray ?? throw new ApiException(400, "Missing nemesis fingerprints"); if (fps.Count > 1000) throw new ApiException(400, "Too many nemeses");
foreach (var fp in fps.Select(NemesisData.Fingerprint).Distinct()) foreach (var entry in inv.Array("NemesisHistory").OfType<JObject>().Where(x => NemesisData.Fingerprint(x["fp"]) == fp).ToArray()) entry.Remove();
return ApiResponse.Json(body);
}
var nemesis = inv["Nemesis"] as JObject ?? throw new ApiException(404, "No active nemesis");
if (mode == "rs") { nemesis["LastEnc"] = nemesis.Value<int>("MissionCount"); return ApiResponse.Json(new { LastEnc = nemesis.Value<int>("LastEnc") }); }
if (mode == "w") return ApiResponse.Json(new JObject { ["target"] = NemesisData.ForGame(nemesis) });
if (mode == "p")
{
var maxSymbol = nemesis.Value<string>("Faction") == "FC_INFESTATION" ? 15 : 9;
if (body["guess"] is not JArray { Count: 3 } guess || guess.Any(x => x.Type != JTokenType.Integer || x.Value<int>() < 0 || x.Value<int>() > maxSymbol)) throw new ApiException(400, "Invalid requiem sequence");
var code = NemesisData.Passcode(nemesis); var result = code.Length == 1 ? Array.IndexOf(guess.Values<int>().ToArray(), code[0]) + 1 : Enumerable.Range(0, 3).Count(i => guess[i].Value<int>() == code[i] || guess[i].Value<int>() == 9);
return ApiResponse.Json(new { GuessResult = result });
}
if (mode == "r") return Requiem(account, nemesis, body);
throw new ApiException(400, "Unknown nemesis operation");
}
private ApiResponse Start(JObject account, JObject body)
{
var inv = account.Obj("Inventory"); var target = body["target"] as JObject ?? throw new ApiException(400, "Missing nemesis target"); var type = target.RequiredString("manifest"); var manifest = NemesisData.Manifest(type);
var fp = NemesisData.Fingerprint(target["fp"] ?? new JValue(0)); if (fp == 0) fp = Wire.Seed();
if (inv["Nemesis"] is JObject current)
{
if (NemesisData.Fingerprint(current["fp"]) == fp && current.Value<string>("manifest") == type) return ApiResponse.Json(new JObject { ["target"] = NemesisData.ForGame(current) });
throw new ApiException(409, "Resolve the current nemesis first");
}
var faction = type.Contains("/Lawyers/", StringComparison.Ordinal) ? "FC_CORPUS" : type.Contains("/InfestedLich/", StringComparison.Ordinal) ? "FC_INFESTATION" : "FC_GRINEER";
if (target["Faction"] is not null && target.Value<string>("Faction") != faction) throw new ApiException(400, "Nemesis faction does not match manifest");
var suit = target.RequiredString("KillingSuit"); if (GameData.Find("Warframes", suit)?["nemesisUpgradeTag"] is null || !inv.Array("Suits").Any(x => x.Value<string>("ItemType") == suit)) throw new ApiException(400, "Progenitor Warframe is not owned");
var weapons = manifest["weapons"]!.Values<string>().ToArray(); var index = -1;
if (weapons.Length > 0)
{
index = new SeededRng(fp).Int(0, weapons.Length - 1); var start = index; var disallowed = (target["DisallowedWeapons"] as JArray ?? []).Values<string>().ToHashSet();
while (disallowed.Contains(weapons[index])) { index = (index + 1) % weapons.Length; if (index == start) throw new ApiException(400, "All nemesis weapons are excluded"); }
}
if (inv.Value<bool>("noNemesis")) return ApiResponse.Json(new JObject());
var created = NemesisData.FromTrade(new JObject { ["fp"] = fp, ["manifest"] = type, ["KillingSuit"] = suit, ["killingDamageType"] = target.Integer("killingDamageType", 0, 32), ["ShoulderHelmet"] = string.IsNullOrEmpty(target.Value<string>("ShoulderHelmet")) ? NemesisData.Helmet(suit) : target.RequiredString("ShoulderHelmet"), ["WeaponIdx"] = index, ["AgentIdx"] = target.Integer("AgentIdx", 0, 100), ["BirthNode"] = target.RequiredString("BirthNode"), ["Faction"] = faction, ["d"] = Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds()) });
created["Traded"] = false; created["PrevOwners"] = 0; inv["Nemesis"] = created; account.Remove("NemesisRequiemReceipt"); return ApiResponse.Json(new JObject { ["target"] = NemesisData.ForGame(created) });
}
private static ApiResponse Fusion(JObject inv, JObject body)
{
var category = body.RequiredString("Category"); if (category is not ("LongGuns" or "Pistols" or "Melee" or "SpaceGuns")) throw new ApiException(400, "Invalid valence fusion category");
var destId = Wire.Id(body["DestWeapon"]); var sourceId = Wire.Id(body["SourceWeapon"]); if (destId == sourceId) throw new ApiException(400, "Cannot fuse a weapon with itself");
var dest = Inventory.Equipment(inv, category, destId); var source = Inventory.Equipment(inv, category, sourceId); Inventory.RequireNotInResearch(inv, sourceId);
if (dest.Value<string>("ItemType") != source.Value<string>("ItemType") || dest.Value<string>("UpgradeType") != "/Lotus/Weapons/Grineer/KuvaLich/Upgrades/InnateDamageRandomMod" || source.Value<string>("UpgradeType") != dest.Value<string>("UpgradeType")) throw new ApiException(400, "Weapons do not support this fusion");
var first = JObject.Parse(dest.RequiredString("UpgradeFingerprint")); var second = JObject.Parse(source.RequiredString("UpgradeFingerprint"));
if (first["buffs"] is not JArray { Count: 1 } firstBuff || second["buffs"] is not JArray { Count: 1 } secondBuff) throw new ApiException(400, "Invalid innate weapon bonus");
var a = ((JObject)firstBuff[0]).Integer("Value", 0, 0x40000000); var b = ((JObject)secondBuff[0]).Integer("Value", 0, 0x40000000);
var damage = Math.Max(.25 + a / (double)0x3fffffff * .35, .25 + b / (double)0x3fffffff * .35) * 1.1; if (damage >= .5794998) damage = .6;
if (body.Value<bool>("UseSourceDmgType")) firstBuff[0]["Tag"] = secondBuff[0]["Tag"]!.DeepClone(); firstBuff[0]["Value"] = (long)((damage - .25) / .35 * 0x3fffffff); dest["UpgradeFingerprint"] = first.ToString(Formatting.None);
source.Remove(); Inventory.FreeSlot(inv, category);
return ApiResponse.Json(new JObject { ["InventoryChanges"] = new JObject { [category] = new JArray(dest.DeepClone()), ["RemovedIdItems"] = new JArray(new JObject { ["ItemId"] = Wire.Oid(sourceId) }), [Inventory.SlotFor(category)!] = new JObject { ["Slots"] = 1 } } });
}
private static JArray KnifeConfig(JObject account)
{
// CurrentLoadOutIds uses the game's enum: DATAKNIFE = 7, MECH = 8.
var inv = account.Obj("Inventory"); var id = (inv["CurrentLoadOutIds"] as JArray)?.ElementAtOrDefault(7); var presets = account.Obj("Loadouts").Array("DATAKNIFE"); var preset = presets.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == Wire.Id(id)) ?? presets.OfType<JObject>().FirstOrDefault();
var knifeId = Wire.Id(preset?["s"]?["ItemId"] ?? preset?["s"]?["itemId"]); var knife = inv.Array("DataKnives").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == knifeId) ?? inv.Array("DataKnives").OfType<JObject>().FirstOrDefault() ?? throw new ApiException(400, "No Parazon equipped");
var config = preset?["s"]?.Value<int>("mod") ?? 0; return (knife["Configs"] as JArray)?.ElementAtOrDefault(config)?["Upgrades"] as JArray ?? throw new ApiException(400, "No Parazon mods equipped");
}
private static JObject ResolveMod(JObject inv, string reference)
{
var mod = inv.Array("Upgrades").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["ItemId"]) == reference);
if (mod is not null) { var type = mod.Value<string>("ItemType") ?? ""; if ((type.Contains("/Immortal/", StringComparison.Ordinal) || type.Contains("/Potency/", StringComparison.Ordinal)) && JObject.Parse(mod.Value<string>("UpgradeFingerprint") ?? "{}").Value<int>("lvl") >= (GameData.Find("Upgrades", type)?.Value<int?>("fusionLimit") ?? 3)) throw new ApiException(409, "Parazon mod has no charges remaining"); return mod; }
if (!inv.Array("RawUpgrades").Any(x => x.Value<string>("ItemType") == reference && x.Value<long>("ItemCount") > 0)) throw new ApiException(400, "Equipped Parazon mod is not owned");
return new JObject { ["ItemType"] = reference };
}
private static void Charge(JObject inv, JArray config, JObject mod, JObject response)
{
var type = mod.RequiredString("ItemType"); var id = Wire.Id(mod["ItemId"]); var created = id.Length == 0;
if (created)
{
Inventory.AddCount(inv, "RawUpgrades", type, -1); id = Wire.NewId(); mod = new JObject { ["ItemId"] = Wire.Oid(id), ["ItemType"] = type, ["UpgradeFingerprint"] = "{\"lvl\":1}" }; inv.Array("Upgrades").Add(mod);
var index = config.Select(x => x.ToString()).ToList().IndexOf(type); if (index < 0) throw new ApiException(400, "Mod is not equipped"); config[index] = id;
}
else { var fingerprint = JObject.Parse(mod.Value<string>("UpgradeFingerprint") ?? "{}"); fingerprint["lvl"] = fingerprint.Value<int>("lvl") + 1; mod["UpgradeFingerprint"] = fingerprint.ToString(Formatting.None); }
response["HasKnife"] = true; response.Array("UpgradeIds").Add(id); response.Array("UpgradeTypes").Add(type); response.Array("UpgradeFingerprints").Add(JObject.Parse(mod.Value<string>("UpgradeFingerprint")!)); response.Array("UpgradeNew").Add(created);
}
private static void Weaken(JObject nemesis) { nemesis["Weakened"] = true; nemesis["InfNodes"] = new JArray(new JObject { ["Node"] = NemesisData.Manifest(nemesis.RequiredString("manifest"))["showdownNode"]!.DeepClone(), ["Influence"] = 1 }); }
private static int AntivirusGain(string? type) => type switch
{
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusAndSpeedOnUseMod" or
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusAndWeaponDamageOnUseMod" or
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusSmallOnSingleUseMod" => 10,
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusLargeOnSingleUseMod" or
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusOnUseMod" => 15,
_ => 0
};
private ApiResponse Requiem(JObject account, JObject nemesis, JObject body)
{
var inv = account.Obj("Inventory"); var key = nemesis["fp"] + ":" + nemesis.Value<int>("MissionCount") + ":" + body.ToString(Formatting.None);
if (account["NemesisRequiemReceipt"] is JObject receipt && receipt.Value<string>("key") == key) return ApiResponse.Json(receipt["response"]);
if (nemesis.Value<bool>("Weakened")) throw new ApiException(409, "Nemesis is already weakened");
var guess = (int)body.Integer("guess", 0, 4095); var position = (int)body.Integer("position", 0, 2); var config = KnifeConfig(account); var response = new JObject(); var code = NemesisData.Passcode(nemesis);
if (code.Length == 1)
{
int[] symbols = [guess & 15, guess >> 4 & 15, guess >> 8 & 15]; var results = symbols.Select(x => x == code[0] ? 2 : 1).ToArray();
// Coda attachment/guess enumeration can differ from physical slot order.
// Validate ownership against the active config, never the client-supplied knife.
// Potency shares the three bottom slots with antivirus, not the utility slots.
var mods = config.Skip(3).Take(3).Where(x => x.Type == JTokenType.String && x.ToString().Length > 0)
.Select(x => ResolveMod(inv, x.ToString())).ToArray();
var available = mods.GroupBy(x => x.RequiredString("ItemType")).ToDictionary(x => x.Key, x => x.Count());
foreach (var symbol in symbols.Where(x => x < 8))
{
var type = SymbolMod(symbol, true);
if (!available.TryGetValue(type, out var count) || count == 0) throw new ApiException(400, "Antivirus sequence does not match equipped mods");
available[type] = count - 1;
}
nemesis.Array("GuessHistory").Add(NemesisData.Encode(symbols, results));
if (results.Contains(2))
{
var gain = 5; foreach (var mod in mods)
{
var extra = AntivirusGain(mod.Value<string>("ItemType"));
if (extra > 0) { gain += extra; Charge(inv, config, mod, response); }
}
nemesis["HenchmenKilled"] = Math.Min(100, nemesis.Value<double>("HenchmenKilled") + gain * (inv.Value<double?>("nemesisAntivirusGainMultiplier") ?? 1));
if (nemesis.Value<double>("HenchmenKilled") >= 100)
{
var antivirus = mods.First(x => x.Value<string>("ItemType") == SymbolMod(code[0], true));
Charge(inv, config, antivirus, response); Weaken(nemesis);
}
}
if (!nemesis.Value<bool>("Weakened")) nemesis["InfNodes"] = NemesisData.Nodes(nemesis.RequiredString("manifest"), 0);
}
else
{
if (config.Count <= 3 + position || ResolveMod(inv, config[3 + position].ToString()).Value<string>("ItemType") != SymbolMod(guess, false)) throw new ApiException(400, "Requiem does not match equipped mod");
var history = nemesis.Array("GuessHistory"); if (position == 0) history.Add(NemesisData.Encode([8, 8, 8], [0, 0, 0])); if (history.Count == 0) throw new ApiException(409, "Start with the first requiem");
var (symbols, results) = NemesisData.Decode(history.Last!.Value<int>()); if (Enumerable.Range(0, position).Any(i => results[i] != 2) || results[position] != 0) throw new ApiException(409, "Requiem sequence is out of order");
var correct = guess == 9 || guess == code[position]; symbols[position] = guess; results[position] = correct ? 2 : 1; history[history.Count - 1] = NemesisData.Encode(symbols, results);
if (!correct) { response["RankIncrease"] = 1; nemesis["Rank"] = Math.Min(nemesis.Value<int>("Rank") + 1, NemesisData.Systems(nemesis.RequiredString("manifest")).Length - 1); nemesis["InfNodes"] = NemesisData.Nodes(nemesis.RequiredString("manifest"), nemesis.Value<int>("Rank")); }
else if (position == 2) { for (var i = 3; i < 6; i++) Charge(inv, config, ResolveMod(inv, config[i].ToString()), response); Weaken(nemesis); }
}
account["NemesisRequiemReceipt"] = new JObject { ["key"] = key, ["response"] = response.DeepClone() }; return ApiResponse.Json(response);
}
}