using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public sealed class TradingApi(TimeProvider clock) { public static readonly HashSet Controllers = ["tradingController"]; private static readonly string[] Counted = ["RawUpgrades", "MiscItems", "Recipes"]; private static readonly string[] Instances = ["RandomUpgrades", "Upgrades", "LongGuns", "Pistols", "Melee"]; public ApiResponse Handle(JObject state, JObject account, ApiRequest request) { var op = request.Q("op"); var id = account.RequiredString("id"); var inv = account.Obj("Inventory"); if (op == "5") { var guild = GuildApi.Own(state, account, request.Q("guildId")); ResearchApi.Access(account); GuildApi.Require(guild, account, 64); if (!int.TryParse(request.Q("tax"), out var tax) || tax is < 0 or > 100) throw new ApiException(400, "Clan tax must be a percentage between 0 and 100"); guild["TradeTax"] = tax; return ApiResponse.Json(tax); } var buddy = request.Q("buddyId") ?? throw new ApiException(400, "Missing trading partner"); if (buddy == id) throw new ApiException(400, "Cannot trade with yourself"); var other = GuildApi.Account(state, buddy); var side = string.CompareOrdinal(id, buddy) < 0 ? "a" : "b"; var theirs = side == "a" ? "b" : "a"; var key = side == "a" ? id + ":" + buddy : buddy + ":" + id; var trades = state.Obj("pendingTrades"); var trade = trades[key] as JObject; if (op == "3") { trades.Remove(key); return ApiResponse.Text(); } if (op == "0") { if (trade is not null) throw new ApiException(409, "A pending trade already exists with this partner"); new PlayerApi(clock).DailyReset(inv); new PlayerApi(clock).DailyReset(other.Obj("Inventory")); Eligible(account); Eligible(other); if (account.Array("Ignored").Any(x => x.ToString() == buddy) || other.Array("Ignored").Any(x => x.ToString() == id)) throw new ApiException(403, "Trading partner is ignored"); JObject? guild = null; if (request.Q("guildId") is string guildId) { guild = GuildApi.Find(state, guildId) ?? throw new ApiException(404, "Trading clan not found"); if (!guild.Array("Members").Any(x => x.Value("status") == 0 && (x.Value("accountId") == id || x.Value("accountId") == buddy))) throw new ApiException(403, "One trading partner must belong to the trading clan"); } trade = new JObject { [side] = id, [theirs] = buddy, ["aOffer"] = EmptyOffer(), ["bOffer"] = EmptyOffer(), ["revision"] = 0, ["clanTax"] = guild?.Value("TradeTax") ?? 10, ["guildId"] = guild?.Value("id") }; trade[side + "Offer"] = Offer(inv, request.ObjectBody()); Reset(trade); trades[key] = trade; } else { if (trade is null) throw new ApiException(404, "Pending trade not found"); switch (op) { case "1": trade[side + "Offer"] = Offer(inv, request.ObjectBody()); trade["revision"] = checked(trade.Value("revision") + 1); Reset(trade); break; case "2": Revision(trade, request); if (!trade.Value("aReady") || !trade.Value("bReady")) throw new ApiException(409, "Both players must confirm the current offer first"); trade[side + "Accepted"] = true; if (trade.Value(theirs + "Accepted")) { Complete(state, trade); trades.Remove(key); return ApiResponse.Text(GameVersion.For(account) < GameVersion.Of("40.0.0") ? "9" : "12"); } return ApiResponse.Text(GameVersion.For(account) < GameVersion.Of("40.0.0") ? "8" : "11"); case "4": break; case "6": Revision(trade, request); trade[side + "Ready"] = true; break; case "7": trade[side + "Ready"] = false; trade["aAccepted"] = trade["bAccepted"] = false; break; default: throw new ApiException(400, "Unknown trading operation"); } } return ApiResponse.Json(new JObject { ["PendingTrades"] = new JArray(Client(trade, id)) }); } public static JArray Pending(JObject state, string accountId) => new(state.Obj("pendingTrades").Properties().Select(x => x.Value).OfType().Where(x => x.Value("a") == accountId || x.Value("b") == accountId).Select(x => Client(x, accountId))); private static JObject Client(JObject trade, string accountId) { var us = trade.Value("a") == accountId ? "a" : "b"; var them = us == "a" ? "b" : "a"; return new JObject { ["ItemId"] = Wire.Oid(trade.RequiredString(them)), ["Giving"] = trade[us + "Offer"]!.DeepClone(), ["Getting"] = trade[them + "Offer"]!.DeepClone(), ["SelfReady"] = trade.Value(us + "Ready"), ["BuddyReady"] = trade.Value(them + "Ready"), ["State"] = trade.Value(us + "Accepted") ? trade.Value(them + "Accepted") ? 4 : 3 : 2, ["Revision"] = trade.Value("revision"), ["ClanTax"] = trade.Value("clanTax") }; } private static JObject EmptyOffer() => new() { ["_SlotOrderInfo"] = new JArray("", "", "", "", "", "") }; private static void Reset(JObject trade) { foreach (var field in new[] { "aReady", "bReady", "aAccepted", "bAccepted" }) trade[field] = false; } private static void Revision(JObject trade, ApiRequest request) { if (!int.TryParse(request.Q("revision"), out var revision) || revision != trade.Value("revision")) throw new ApiException(409, "Trade offer has changed"); } private static void Eligible(JObject account) { var inv = account.Obj("Inventory"); if (account.Value("Banned")) throw new ApiException(403, "Trading account is banned"); if (!inv.Value("infiniteTrades") && inv.Value("TradesRemaining") <= 0) throw new ApiException(409, "No trades remaining today"); if (inv.Value("PlayerLevel") < 2) throw new ApiException(403, "Trading requires mastery rank 2"); } private static JObject Offer(JObject inv, JObject upload) { var result = EmptyOffer(); var unique = new HashSet(); var slots = 0; foreach (var field in upload.Properties()) if (!Counted.Contains(field.Name) && !Instances.Contains(field.Name) && field.Name is not ("FusionTreasures" or "NemesisHistory" or "PremiumCredits" or "_SlotOrderInfo")) throw new ApiException(400, "Unknown trade category"); if (upload["_SlotOrderInfo"] is JArray order) { if (order.Count > 6 || order.Any(x => x.Type != JTokenType.String || x.ToString().Length > 512)) throw new ApiException(400, "Invalid trade slot order"); result["_SlotOrderInfo"] = order.DeepClone(); } foreach (var category in Counted) { foreach (var item in Entries(upload, category)) { var type = item.RequiredString("ItemType"); var count = item.Integer("ItemCount", 1, 1000000); if (!unique.Add(category + ":" + type)) throw new ApiException(400, "Duplicate trade item"); if (!inv.Array(category).Any(x => x.Value("ItemType") == type && x.Value("ItemCount") >= count)) throw new ApiException(400, "Offered items are not owned"); var meta = category == "RawUpgrades" ? GameData.Find("Upgrades", type) ?? GameData.Find("Arcanes", type) : GameData.Find(category == "Recipes" ? "Recipes" : "Resources", type); if (category == "Recipes" && meta?.Value("consumeOnUse") == true && inv.Array("Recipes").First(x => x.Value("ItemType") == type).Value("ItemCount") - inv.Array("PendingRecipes").Count(x => (x.Value("OwnedRecipeType") ?? FoundryApi.OwnedRecipe(x.Value("ItemType") ?? "")) == type) < count) throw new ApiException(409, "Blueprint is reserved by a pending recipe"); if (meta?.Value("tradable") == false) throw new ApiException(400, "Item cannot be traded"); result.Array(category).Add(new JObject { ["ItemType"] = type, ["ItemCount"] = count }); slots++; } } foreach (var category in Instances) { var field = category == "RandomUpgrades" ? "Upgrades" : category; foreach (var item in Entries(upload, category)) { var id = Wire.Id(item["ItemId"]); if (id.Length != 24 || !unique.Add(id)) throw new ApiException(400, "Invalid or duplicate item identifier"); var owned = inv.Array(field).OfType().FirstOrDefault(x => Wire.Id(x["ItemId"]) == id) ?? throw new ApiException(404, "Trade item is not owned"); var type = owned.RequiredString("ItemType"); if (item["ItemType"] is JToken asked && asked.ToString() != type) throw new ApiException(400, "Offered item type does not match its identifier"); if (field != "Upgrades") { if (GameData.Find("Weapons", type)?.Value("tradable") != true || owned.Value("XP") > 0) throw new ApiException(400, "Only unused tradable weapons can be traded"); } else if ((GameData.Find("Upgrades", type) ?? GameData.Find("Arcanes", type))?.Value("tradable") == false) throw new ApiException(400, "Mod cannot be traded"); Inventory.RequireNotInResearch(inv, id); result.Array(category).Add(owned.DeepClone()); slots++; } } foreach (var item in Entries(upload, "FusionTreasures")) { var type = item.RequiredString("ItemType"); var count = item.Integer("ItemCount", 1, 1000000); var sockets = item.Integer("Sockets", 0, 65535); if (!unique.Add(type + ":" + sockets) || !inv.Array("FusionTreasures").Any(x => x.Value("ItemType") == type && x.Value("Sockets") == sockets && x.Value("ItemCount") >= count)) throw new ApiException(400, "Sculpture stack is duplicated or not owned"); result.Array("FusionTreasures").Add(new JObject { ["ItemType"] = type, ["ItemCount"] = count, ["Sockets"] = sockets }); slots++; } if (upload["NemesisHistory"] is JObject nemesis) { var owned = inv.Array("NemesisHistory").OfType().FirstOrDefault(x => x["fp"]?.ToString() == nemesis["fp"]?.ToString()) ?? throw new ApiException(404, "Converted nemesis is not owned"); if (owned.Value("k") || owned.Value("Traded") || owned.Value("PrevOwners") > 0) throw new ApiException(400, "Nemesis cannot be traded again"); NemesisData.Systems(owned.RequiredString("manifest")); result["NemesisHistory"] = owned.DeepClone(); slots++; } if (upload["PremiumCredits"] is not null) { var platinum = upload.Integer("PremiumCredits", 0, 999999999); if (!AccountRules.InfiniteCurrency(inv, "PremiumCredits") && platinum > inv.Value("PremiumCredits") - inv.Value("PremiumCreditsFree")) throw new ApiException(400, "Insufficient tradable platinum"); result["PremiumCredits"] = platinum; if (platinum > 0) slots++; } if (slots > 6) throw new ApiException(400, "A trade offer may contain at most six slots"); return result; } private static IEnumerable Entries(JObject offer, string key) { if (offer[key] is null) return []; if (offer[key] is not JArray array || array.Any(x => x is not JObject)) throw new ApiException(400, "Invalid trade item array"); return array.OfType(); } private static void Complete(JObject state, JObject trade) { var a = GuildApi.Account(state, trade.RequiredString("a")); var b = GuildApi.Account(state, trade.RequiredString("b")); Eligible(a); Eligible(b); var ai = a.Obj("Inventory"); var bi = b.Obj("Inventory"); var ao = (JObject)trade["aOffer"]!; var bo = (JObject)trade["bOffer"]!; if (!JToken.DeepEquals(ao, Offer(ai, ao)) || !JToken.DeepEquals(bo, Offer(bi, bo))) throw new ApiException(409, "An offered item changed; update and confirm the trade again"); // Remove both offers before assigning either one, so occupied slots can be exchanged atomically. if (!ai.Value("tradesDontTouchInventory")) Transfer(ai, ao, -1); if (!bi.Value("tradesDontTouchInventory")) Transfer(bi, bo, -1); if (!ai.Value("tradesDontTouchInventory")) { Transfer(ai, bo, 1); Charge(state, trade, ai, bo); if (!ai.Value("infiniteTrades")) ai["TradesRemaining"] = ai.Value("TradesRemaining") - 1; } if (!bi.Value("tradesDontTouchInventory")) { Transfer(bi, ao, 1); Charge(state, trade, bi, ao); if (!bi.Value("infiniteTrades")) bi["TradesRemaining"] = bi.Value("TradesRemaining") - 1; } } private static void Transfer(JObject inv, JObject offer, int direction) { foreach (var category in Counted) foreach (var item in Entries(offer, category)) Inventory.AddCount(inv, category, item.RequiredString("ItemType"), item.Integer("ItemCount", 1) * direction); foreach (var category in Instances) foreach (var item in Entries(offer, category)) { var field = category == "RandomUpgrades" ? "Upgrades" : category; var id = Wire.Id(item["ItemId"]); if (direction < 0) { var owned = inv.Array(field).First(x => Wire.Id(x["ItemId"]) == id); owned.Remove(); Inventory.FreeSlot(inv, field); } else { if (inv.Array(field).Any(x => Wire.Id(x["ItemId"]) == id)) throw new ApiException(409, "Recipient already owns this item identifier"); if (field != "Upgrades" && GameData.Find("Weapons", item.Value("ItemType"))?.Value("masteryReq") > inv.Value("PlayerLevel")) throw new ApiException(403, "Recipient does not meet the weapon mastery requirement"); Inventory.OccupySlots(inv, field, 1, false); inv.Array(field).Add(item.DeepClone()); } } foreach (var item in Entries(offer, "FusionTreasures")) VaultApi.Treasure(inv, "FusionTreasures", item.RequiredString("ItemType"), item.Value("Sockets"), item.Integer("ItemCount", 1) * direction); if (offer["NemesisHistory"] is JObject nemesis) { if (direction < 0) inv.Array("NemesisHistory").First(x => x["fp"]?.ToString() == nemesis["fp"]?.ToString()).Remove(); else { if (inv["Nemesis"] is JObject { Count: > 0 }) throw new ApiException(409, "Recipient already has an active nemesis"); inv["Nemesis"] = NemesisData.FromTrade(nemesis); } } if (offer.Value("PremiumCredits") > 0) { if (direction < 0 && AccountRules.InfiniteCurrency(inv, "PremiumCredits")) return; var value = checked(inv.Value("PremiumCredits") + offer.Value("PremiumCredits") * direction); if (value < inv.Value("PremiumCreditsFree") || value > 999999999) throw new ApiException(400, "Invalid platinum balance after trade"); inv["PremiumCredits"] = value; } } private static long Rarity(string? rarity) => rarity switch { "UNCOMMON" => 4000, "RARE" => 8000, "LEGENDARY" => 1000000, _ => 2000 }; public static long Tax(JObject offer) { long value = offer.Value("PremiumCredits") * 500 + Entries(offer, "RandomUpgrades").Count() * 8000; foreach (var item in Entries(offer, "Upgrades")) { var type = item.RequiredString("ItemType"); var arcane = GameData.Find("Arcanes", type); var rank = item.Value("UpgradeFingerprint") is string fp ? JObject.Parse(fp).Value("lvl") : 0; if (arcane is not null && rank is < 0 or > 5) throw new ApiException(400, "Invalid arcane rank"); value = checked(value + (arcane?.Value("rarity") == "LEGENDARY" ? new[] { 100000, 300000, 600000, 1000000, 1500000, 2100000 }[rank] : Rarity((arcane ?? GameData.Find("Upgrades", type))?.Value("rarity")) * (arcane is null ? 1 : new[] { 1, 3, 6, 10, 15, 21 }[rank]))); } foreach (var category in Counted) foreach (var item in Entries(offer, category)) { var type = item.RequiredString("ItemType"); var meta = category == "RawUpgrades" ? GameData.Find("Upgrades", type) ?? GameData.Find("Arcanes", type) : GameData.Find("Resources", type); var rate = category == "Recipes" ? 2000 : type.StartsWith("/Lotus/Types/Game/Projections/T3", StringComparison.Ordinal) || type.StartsWith("/Lotus/Types/Game/Projections/T4", StringComparison.Ordinal) ? 4000 : Rarity(meta?.Value("rarity")); value = checked(value + rate * item.Integer("ItemCount", 1)); } value += new[] { "LongGuns", "Pistols", "Melee" }.Sum(x => Entries(offer, x).Count()) * 2000; foreach (var item in Entries(offer, "FusionTreasures")) value = checked(value + item.Integer("ItemCount", 1) * (item.Value("Sockets") > 0 ? 12000 : 4000)); if (offer["NemesisHistory"] is JObject) value += 8000; return value; } private static void Charge(JObject state, JObject trade, JObject inv, JObject incoming) { var tax = Tax(incoming); var extra = tax * trade.Value("clanTax") / 100; if (!inv.Value("infiniteCredits")) Inventory.ChangeCurrency(inv, "RegularCredits", -checked(tax + extra)); if (extra > 0 && GuildApi.Find(state, trade.Value("guildId")) is JObject guild) ResearchApi.Credit(guild, "VaultRegularCredits", extra); } }