using Newtonsoft.Json; using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public sealed class PurchaseApi(ItemCatalog catalog, TimeProvider clock, bool syncOfficialEvents = true) { private long Price(string type, bool premium, int durability, JArray sales, int depth = 0) { if (depth > 8) throw new ApiException(400, "Recursive bundle price"); var (category, meta) = catalog.Get(type); var sale = sales.FirstOrDefault(x => catalog.ResolveType(x.Value("TypeName") ?? "") == catalog.ResolveType(type)); if (sale?[premium ? "PremiumOverride" : "RegularOverride"] is JToken price) return price.Value(); if (category == "Boosters") return premium && !type.Contains("Blessing", StringComparison.Ordinal) ? durability == 2 ? 200 : 40L * (durability + 1) : throw new ApiException(400, "Booster is not sold for this currency"); if (meta[premium ? "platinumCost" : "creditsCost"] is JToken cost && cost.Type == JTokenType.Integer) return cost.Value(); if (category == "Bundles") { var total = 0L; foreach (var part in (meta["components"] as JArray ?? []).OfType()) total = checked(total + Price(part.RequiredString("typeName"), premium, Array.IndexOf(new[] { 3, 7, 30, 90 }, part.Value("durabilityDays") ?? 3), sales, depth + 1) * part.Integer("purchaseQuantity", 1, 100000)); return (long)Math.Floor(total * (1 - (meta.Value("packageDiscount") ?? .25)) + .5); } throw new ApiException(400, "Item has no price for the selected currency"); } public ApiResponse Handle(JObject state, JObject account, ApiRequest request, bool gift = false) { var body = request.ObjectBody(); var p = body["PurchaseParams"] as JObject ?? new JObject { ["StoreItem"] = request.Q("productName") ?? body.Value("productName"), ["Quantity"] = body.Value("quantity") ?? 1, ["UsePremium"] = (request.Q("usePremium") ?? body.Value("usePremium")) == "1", ["Source"] = body["voidTraderId"] is null ? 0 : 1, ["SourceId"] = body["voidTraderId"]?.DeepClone(), ["Durability"] = int.TryParse(request.Q("durability"), out var d) ? d : 0 }; var inv = account.Obj("Inventory"); var source = (int)p.Integer("Source", 0, 24); var count = (int)p.Integer("Quantity", 1, 100); var premium = p.Value("UsePremium"); var durability = (int)(p["Durability"] is null ? 0 : p.Integer("Durability", 0, 3)); var type = p.RequiredString("StoreItem").Replace("/Brass Knuckles/", "/BrassKnuckles/", StringComparison.Ordinal); var (category, meta) = catalog.Get(type); var delta = new JObject(); var response = new JObject { ["InventoryChanges"] = delta }; var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); var build = GameVersion.For(account); var quantity = count; ulong? seed = null; if (gift && (source is not (0 or 3) || source == 0 && !premium)) throw new ApiException(400, "Only platinum market purchases and daily deals can be gifted"); void Currency(string field, long cost) { if (cost < 0) throw new ApiException(400, "Invalid price"); if (AccountRules.InfiniteCurrency(inv, field)) return; if (field == "RegularCredits" && inv.Value("dontSubtractPurchaseCreditCost") || field == "PremiumCredits" && inv.Value("dontSubtractPurchasePlatinumCost")) return; if (gift && field == "PremiumCredits") { if (inv.Value(field) - inv.Value("PremiumCreditsFree") < cost) throw new ApiException(400, "Insufficient paid platinum"); inv[field] = inv.Value(field) - cost; Inventory.Combine(delta, new JObject { [field] = -cost }); } else Inventory.Combine(delta, Inventory.ChangeCurrency(inv, field, -cost)); } void Items(JArray prices) { if (inv.Value("dontSubtractPurchaseItemCost")) return; foreach (var item in prices.OfType()) { var itemType = item.RequiredString("ItemType"); var itemCount = checked(count * item.Integer("ItemCount")); var itemCategory = catalog.Get(itemType).Category; if (!Inventory.CountedKeys.Contains(itemCategory)) throw new ApiException(400, "Vendor requires a counted payment item"); Inventory.AddCount(inv, itemCategory, itemType, -itemCount); Inventory.Combine(delta, new JObject { [itemCategory] = new JArray(new JObject { ["ItemType"] = itemType, ["ItemCount"] = -itemCount }) }); } } void StandingCost(string tag, long price) { if (inv.Value("dontSubtractPurchaseStandingCost")) return; var modifications = new JArray(); Standing.Spend(inv, tag, checked(price * count), modifications); response.Array("Standing").Add(new JObject { ["Tag"] = tag, ["Standing"] = price * count }); } if (source == 2) { var tag = p.RequiredString("SyndicateTag"); var favour = (Standing.Metadata(tag)["favours"] as JArray ?? []).OfType().FirstOrDefault(x => x.Value("storeItem") == type) ?? throw new ApiException(400, "Syndicate favour is not offered"); var affiliation = Standing.Affiliation(inv, tag); if (affiliation.Value("Title") < favour.Value("requiredLevel")) throw new ApiException(403, "Syndicate rank is too low"); if (p.Value("UseFreeFavor")) { var title = affiliation.Array("FreeFavorsEarned").FirstOrDefault(x => !affiliation.Array("FreeFavorsUsed").Any(y => JToken.DeepEquals(x, y)) && x.Value() == favour.Value("requiredLevel")); if (count != 1 || !favour.Value("rankUpReward") || title is null) throw new ApiException(400, "No applicable free favour"); affiliation.Array("FreeFavorsUsed").Add(title.DeepClone()); response["FreeFavorsUsed"] = new JArray(new JObject { ["Tag"] = tag, ["Title"] = title.DeepClone() }); } else { Currency("RegularCredits", favour.Value("creditsCost") * count); if (favour.Value("standingCost") > 0) StandingCost(tag, favour.Value("standingCost")); } } else if (source is 1 or 18) { var world = WorldApi.Generate(state, account.Value("BuildLabel") ?? "2026.05.13.13.07", now, syncOfficialEvents); var traders = world[source == 1 ? "VoidTraders" : "PrimeVaultTraders"] as JArray ?? []; var trader = traders.OfType().FirstOrDefault(x => Wire.Id(x["_id"]) == p.Value("SourceId")) ?? throw new ApiException(404, "Trader not found"); var worldTime = world.Value("Time") * 1000; if (Wire.DateMs(trader["Activation"]) > worldTime || Wire.DateMs(trader["Expiry"]) <= worldTime) throw new ApiException(409, "Trader is not currently available"); var offer = trader.Array("Manifest").Concat(trader["EvergreenManifest"] as JArray ?? []).OfType().FirstOrDefault(x => x.Value("ItemType") == type) ?? throw new ApiException(400, "Item is not offered by this trader"); if (source == 1) { Currency("RegularCredits", offer.Value("RegularPrice") * count); Items(new JArray(new JObject { ["ItemType"] = "/Lotus/Types/Items/MiscItems/PrimeBucks", ["ItemCount"] = offer.Value("PrimePrice") })); } else if (offer.Value("RegularPrice") > 0) Items(new JArray(new JObject { ["ItemType"] = "/Lotus/Types/Items/MiscItems/SchismKey", ["ItemCount"] = offer.Value("RegularPrice") })); else Currency("PrimeTokens", offer.Value("PrimePrice") * count); if (offer.Value("Limit") > 0) Tally(inv, delta, source == 1 ? "VoidTrader" : "PrimeVaultTrader", type, count, offer.Value("Limit"), Wire.DateMs(trader["Expiry"]), now); } else if (source == 3) { var worldTime = WorldClock.ReportedTime(now, state.Obj("worldState")); var deals = WorldTrade.DailyDeals(state, worldTime, build, state.Obj("worldState")); var deal = deals.OfType().FirstOrDefault(x => x.Value("StoreItem") == type && Wire.DateMs(x["Activation"]) <= worldTime && Wire.DateMs(x["Expiry"]) > worldTime) ?? throw new ApiException(404, "Daily deal not found"); if (count != 1 || deal.Value("AmountSold") >= deal.Value("AmountTotal")) throw new ApiException(409, "Daily deal is out of stock"); Tally(inv, delta, "DailyDeal", type, 1, 1, Wire.DateMs(deal["Expiry"]), worldTime); Currency("PremiumCredits", deal.Integer("SalePrice")); var original = state.Obj("worldRuntime").Array("DailyDeals").First(x => x.Value("StoreItem") == type); original["AmountSold"] = original.Value("AmountSold") + 1; inv.Array("UsedDailyDeals").UniqueAdd(type); response["DailyDealUsed"] = type; premium = true; } else if (source == 7) { var vendor = VendorApi.Generate(state, VendorApi.ResolveId(p.RequiredString("SourceId"), build), build, now, inv); var itemId = p.Value("ExtraPurchaseInfoJson") is { Length: > 0 } extra ? JObject.Parse(extra).Value("ItemId") : null; var offer = vendor.Array("ItemManifest").OfType().FirstOrDefault(x => itemId is null ? x.Value("StoreItem") == type : Wire.Id(x["Id"]) == itemId && x.Value("StoreItem") == type) ?? throw new ApiException(400, "Vendor offer is not available"); if (Wire.DateMs(offer["Expiry"]) <= now) throw new ApiException(409, "Vendor offer expired"); if (offer.Value("Affiliation") is string tag) { if (Standing.Affiliation(inv, tag).Value("Title") < offer.Value("MinAffiliationRank")) throw new ApiException(403, "Vendor rank requirement is not met"); if (offer.Value("StandingCost") > 0) StandingCost(tag, offer.Value("StandingCost")); } if (offer["RegularPrice"] is JArray credits) Currency("RegularCredits", credits[0].Value() * count); if (offer["PremiumPrice"] is JArray platinum) Currency("PremiumCredits", platinum[0].Value() * count); if (offer["ItemPrices"] is JArray prices) Items(prices); if (offer["FocusXpCost"] is JObject focus) { var polarity = focus.RequiredString("polarity"); var cost = checked(focus.Integer("cost") * count); if (inv.Obj("FocusXP").Value(polarity) < cost) throw new ApiException(400, "Insufficient focus points"); inv.Obj("FocusXP")[polarity] = inv.Obj("FocusXP").Value(polarity) - cost; response["FocusCost"] = new JObject { ["Polarity"] = polarity, ["Cost"] = cost }; } Tally(inv, delta, vendor.RequiredString("TypeName"), Wire.Id(offer["Id"]), count, offer.Value("PurchaseQuantityLimit"), p.Value("IsWeekly") ? WorldData.Epoch + (WorldData.WeekOf(now) + 1L) * WorldData.Week : Wire.DateMs(offer["Expiry"]), now); quantity = checked(count * (int)offer.Integer("QuantityMultiplier", 1, 100000)); if (ulong.TryParse(offer.Value("LocTagRandSeed"), out var s)) seed = s; } else { var world = WorldApi.Generate(state, account.Value("BuildLabel")!, now, syncOfficialEvents); var worldTime = world.Value("Time") * 1000; var sales = new JArray(world.Array("FlashSales").Where(x => (x["StartDate"] is null || Wire.DateMs(x["StartDate"]) <= worldTime) && (x["EndDate"] is null || Wire.DateMs(x["EndDate"]) > worldTime))); if (meta.Value("excludeFromMarket") && !sales.Any(x => catalog.ResolveType(x.Value("TypeName") ?? "") == catalog.ResolveType(type) && x.Value("ShowInMarket") != false)) throw new ApiException(400, "Item is not available in the market"); var price = checked(Price(type, premium, durability, sales) * count); if (p.Value("ExpectedPrice") > 0 && p.Value("ExpectedPrice") != price) throw new ApiException(409, "Market price changed"); Currency(premium ? "PremiumCredits" : "RegularCredits", price); } if (category is "MiscItems" or "Consumables") quantity = checked(quantity * (meta.Value("purchaseQuantity") ?? 1)); if (gift) return ApiResponse.Json(response); var packResults = new JArray(); Inventory.Combine(delta, new ItemAcquisition(catalog, clock, account, packResults).Add(inv, type, quantity, premium, durabilityDays: new[] { 3, 7, 30, 90 }[durability], seed: seed)); if (packResults.Count > 0) { var packed = string.Concat(packResults.Select(x => x.Value("StoreItem") + "," + x["Fingerprint"]!.ToString(Formatting.None) + ";")); response["BoosterPackItems"] = packed; response["Body"] = packed.Replace("{", "", StringComparison.Ordinal).Replace("}", "", StringComparison.Ordinal).Replace("\"", "", StringComparison.Ordinal).Replace(':', '='); } if (request.Method == "GET") return response.Value("Body") is string legacyBody ? ApiResponse.Text(legacyBody.Replace("/StoreItems", "", StringComparison.Ordinal)) : ApiResponse.Text(catalog.ResolveType(type)); return ApiResponse.Json(response); } public static void Tally(JObject inv, JObject delta, string vendor, string id, int count, int limit, long expiry, long now) { if (inv.Value("noVendorPurchaseLimits")) return; var entry = inv.Array("RecentVendorPurchases").OfType().FirstOrDefault(x => x.Value("VendorType") == vendor); if (entry is null) { entry = new JObject { ["VendorType"] = vendor, ["PurchaseHistory"] = new JArray() }; inv.Array("RecentVendorPurchases").Add(entry); } var purchase = entry.Array("PurchaseHistory").OfType().FirstOrDefault(x => x.Value("ItemId") == id); if (purchase is null) { purchase = new JObject { ["ItemId"] = id, ["NumPurchased"] = 0, ["Expiry"] = Wire.Date(expiry) }; entry.Array("PurchaseHistory").Add(purchase); } var previous = Wire.DateMs(purchase["Expiry"]) <= now ? 0 : purchase.Value("NumPurchased"); if (limit > 0 && previous + count > limit) throw new ApiException(409, "Vendor purchase limit exceeded"); purchase["NumPurchased"] = checked(previous + count); purchase["Expiry"] = Wire.Date(expiry); var change = new JObject { ["VendorType"] = vendor, ["PurchaseHistory"] = new JArray(purchase.DeepClone()) }; delta["NewVendorPurchase"] = change; delta["RecentVendorPurchases"] = change.DeepClone(); } }