using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public sealed class VendorApi(TimeProvider clock) { public static readonly HashSet Controllers = ["getVendorInfoController"]; public static uint Hash(string text) { uint hash = 2166136261; // Upstream JavaScript multiplies in IEEE-754 double before the bitwise truncation. foreach (var ch in text) { hash = (hash ^ ch) & 0x7fffffff; hash = (uint)((long)(hash * (double)16777619) & 0x7fffffff); } return hash; } private const string Coda = "/Lotus/Types/Game/VendorManifests/TheHex/InfestedLichWeaponVendorManifest", Tenet = "/Lotus/Types/Game/VendorManifests/Hubs/PerrinSequenceWeaponVendorManifest"; public static string Id(string type) => type == Coda ? "67dadc30e4b6e0e5979c8d84" : type == Tenet ? "60ad3b6ec96976e97d227e19" : "5be4a159b144f3cd" + Hash(type).ToString("x8"); public static JObject? Metadata(string type) => GameData.Find("Vendors", type) ?? WorldData.Get("supplementalVendors")[type] as JObject; public static string ResolveId(string id, long build) { if (Metadata(id) is not null) return id; foreach (var type in GameData.Table("Vendors").Properties().Select(x => x.Name).Concat(((JObject)WorldData.Get("supplementalVendors")).Properties().Select(x => x.Name)).Concat(((JObject)WorldData.Get("legacyNightwaveVendorManifest")).Properties().Select(x => x.Name))) if (Id(type) == id) return type; throw new ApiException(404, "Unknown vendor identifier"); } public ApiResponse Handle(JObject state, JObject? account, string buildLabel, ApiRequest request) => ApiResponse.Json(new JObject { ["VendorInfo"] = Generate(state, request.Q("vendor") ?? throw new ApiException(400, "Missing vendor"), GameVersion.Parse(buildLabel), clock.GetUtcNow().ToUnixTimeMilliseconds(), account?.Obj("Inventory")) }); private static (int Min, int Max) Range(JToken? token, int fallback = 0) => token is JObject range ? (range.Value("minValue"), range.Value("maxValue")) : (token?.Value() ?? fallback, token?.Value() ?? fallback); private static long Gcd(long a, long b) { while (b != 0) (a, b) = (b, a % b); return a; } private static string Key(JObject raw) => raw.RequiredString("storeItem") + "x" + raw.Value("quantity") + (raw["itemPrices"] is JArray prices && prices.Count > 0 ? ":" + prices[0]!.Value("ItemType") : ""); public static JObject Generate(JObject state, string type, long build, long now, JObject? inventory = null) { var meta = Metadata(type); var idType = type; if (type.StartsWith("/Lotus/Types/Game/VendorManifests/Events/RadioLegion", StringComparison.Ordinal)) { var waveTag = WorldSeasons.NightwaveTag(build, state["worldState"]?.Value("nightwaveOverride")) ?? throw new ApiException(404, "Nightwave is not active"); var season = WorldData.Get("nightwaveTagToSeason")[waveTag]!; var legacy = ((JObject)WorldData.Get("legacyNightwaveVendorManifest")).Properties().ElementAtOrDefault(season.Value()); if (legacy is not null) { meta = (JObject)legacy.Value; idType = legacy.Name; } } if (meta is null) throw new ApiException(404, "Unknown vendor"); var vendorId = Id(idType); var items = ((JArray)meta["items"]!).OfType().ToArray(); var full = state.Obj("config").Value("fullyStockedVendors") ?? state.Obj("worldState").Value("fullyStockedVendors"); var storage = state.Obj("worldRuntime").Obj("Vendors"); var cacheKey = vendorId + (full ? ":full" : ":normal"); var cached = storage[cacheKey] as JObject; if (cached is null) { cached = new JObject { ["_id"] = Wire.Oid(vendorId), ["TypeName"] = type, ["ItemManifest"] = new JArray(), ["Expiry"] = Wire.Date(0) }; storage[cacheKey] = cached; } var seedType = meta.Value("randomSeedType"); if (type is Coda or Tenet) { seedType = "VRST_WEAPON"; cached["WeaponUpgradeValueAttenuationExponent"] = 2.25; if (type == Coda) cached["RequiredGoalTag"] = ""; } if (seedType is not null) cached["RandomSeedType"] = seedType; var duration = 0L; foreach (var raw in items.Where(x => !x.Value("alwaysOffered"))) { if (!raw.Value("rotatedWeekly") && raw["durationHours"] is not JValue) { duration = 1; break; } duration = Gcd(duration, raw.Value("rotatedWeekly") ? 168 : raw.Value("durationHours")); } duration *= WorldData.Hour; var offset = type == Coda ? 1740960000000L : type == Tenet ? 1744934400000L : WorldData.Epoch; if (type is Coda or Tenet) duration = 4 * WorldData.Day; var durations = items.Where(x => x["durationHours"] is not null).Select(x => Range(x["durationHours"])).ToArray(); var minHours = durations.Length > 0 ? durations.Min(x => x.Min) : 0; var maxHours = durations.Length > 0 ? durations.Max(x => x.Max) : 0; var cursor = now - (minHours != maxHours ? (maxHours - 1L) * WorldData.Hour : 0); var offers = cached.Array("ItemManifest"); var guard = 0; while (Wire.DateMs(cached["Expiry"]) <= now) { if (++guard > 1000) throw new ApiException(400, "Vendor rotation could not converge"); foreach (var expired in offers.OfType().Where(x => Wire.DateMs(x["Expiry"]) <= cursor).ToArray()) expired.Remove(); var cycle = duration == 0 ? 0 : (int)((cursor - offset) / duration); var start = duration == 0 ? 0 : offset + cycle * duration; var rng = new SeededRng((ulong)SeededRng.Mix(unchecked((int)Convert.ToUInt32(vendorId[16..], 16)), cycle)); var added = new List(); if (meta.Value("isOneBinPerCycle")) added.AddRange(items.Where(x => full || x.Value("bin") == cycle % 2)); else { var capacities = new Dictionary(StringComparer.Ordinal); foreach (var raw in items) capacities[Key(raw)] = 1 + raw.Value("duplicates"); var bins = (meta["numItemsPerBin"] as JArray ?? []).Select((x, i) => (Count: x.Value(), Bin: i)).ToDictionary(x => x.Bin, x => x.Count); var missing = bins.Values.Sum(); void UseBin(int bin) { if (bins.GetValueOrDefault(bin) != 0) { bins[bin]--; missing--; } } foreach (var offer in offers.OfType()) { var key = offer.RequiredString("_key"); capacities[key] = capacities.GetValueOrDefault(key) - 1; UseBin(int.Parse(offer.RequiredString("Bin")[4..])); } var permanent = 0; var counted = 0; var insertion = 0; foreach (var raw in items) if (raw.Value("alwaysOffered") || raw.Value("rotatedWeekly")) { permanent++; var key = Key(raw); if (capacities[key] != 0) { capacities[key]--; added.Add(raw); insertion++; } UseBin(raw.Value("bin")); } else counted += 1 + raw.Value("duplicates"); var number = Range(meta["numItems"]); var random = meta["numItems"] is not null && (number.Min != number.Max || number.Min != counted); var target = full ? permanent + Math.Max(capacities.Values.Sum(), missing == 0 ? 0 : bins.Values.Sum()) : meta["numItems"] is not null ? permanent + Math.Min(capacities.Values.Sum(), random ? rng.Int(number.Min, number.Max) : number.Min) : items.Length; var rollable = new JArray(items.Where(x => x["probability"] is not null).Select(x => x.DeepClone())); var index = 0; for (var attempts = 0; offers.Count + added.Count < target; attempts++) { if (attempts > 10000 || rollable.Count == 0) throw new ApiException(400, "Vendor pool cannot satisfy its offer limits"); var raw = random ? rng.Reward(rollable)! : (JObject)rollable[index++ % rollable.Count]; var key = Key(raw); var bin = raw.Value("bin"); if (capacities[key] <= 0 || missing != 0 && bins.GetValueOrDefault(bin) == 0) continue; capacities[key]--; UseBin(bin); added.Insert(insertion, raw); } } foreach (var raw in added) { var hours = Range(raw["durationHours"], (int)Math.Max(1, duration / WorldData.Hour)); var expiry = raw.Value("alwaysOffered") ? 2051240400000L : start + (raw.Value("rotatedWeekly") ? WorldData.Week : rng.Int(hours.Min, hours.Max) * WorldData.Hour); var item = new JObject { ["StoreItem"] = raw["storeItem"]!.DeepClone(), ["Bin"] = "BIN_" + raw.Value("bin"), ["QuantityMultiplier"] = raw.Value("quantity"), ["Expiry"] = Wire.Date(expiry), ["AllowMultipurchase"] = raw.Value("purchaseLimit") != 1, ["Id"] = Wire.Oid(unchecked((uint)(start / 1000)).ToString("x8") + vendorId[8..16] + rng.Long(0, uint.MaxValue).ToString("x8")), ["_key"] = Key(raw) }; if (raw["itemPrices"] is JArray prices) item["ItemPrices"] = new JArray(prices.OfType().Select(x => { var price = (JObject)x.DeepClone(); price["ProductCategory"] = "MiscItems"; return price; })); foreach (var (from, to) in new[] { ("purchaseLimit", "PurchaseQuantityLimit"), ("rotatedWeekly", "RotatedWeekly"), ("focusXpCost", "FocusXpCost") }) if (raw[from] is JToken v) item[to] = v.DeepClone(); if (raw["syndicate"] is JObject affiliation) foreach (var (from, to) in new[] { ("tag", "Affiliation"), ("minRank", "MinAffiliationRank"), ("reductionPerPositiveRank", "ReductionPerPositiveRank"), ("increasePerNegativeRank", "IncreasePerNegativeRank"), ("standingCost", "StandingCost") }) if (affiliation[from] is JToken v) item[to] = v.DeepClone(); for (var i = 0; i < raw.Value("numRandomItemPrices"); i++) { var pool = ((JArray)meta["randomItemPricesPerBin"]![raw.Value("bin")]!).OfType().ToArray(); JObject price; var retries = 0; do { if (++retries > 10000) throw new ApiException(400, "Vendor has insufficient distinct payment items"); price = rng.Element(pool); } while (item.Array("ItemPrices").Any(x => x.Value("ItemType") == price.Value("type"))); var range = Range(price["count"]); item.Array("ItemPrices").Add(new JObject { ["ItemType"] = price["type"]!.DeepClone(), ["ItemCount"] = rng.Int(range.Min, range.Max), ["ProductCategory"] = "MiscItems" }); } foreach (var (field, output) in new[] { ("credits", "RegularPrice"), ("platinum", "PremiumPrice") }) if (raw[field] is JToken token) { var range = Range(token); var step = field == "credits" && token is JObject r ? r.Value("step") ?? 1 : 1; var value = rng.Int(range.Min / step, range.Max / step) * step; if (value != 0) item[output] = new JArray(value, value); } if (seedType is not null) { var low = rng.Long(0, uint.MaxValue); item["LocTagRandSeed"] = seedType == "VRST_WEAPON" ? new JValue(((ulong)rng.Long(0, uint.MaxValue) << 32 | (ulong)low).ToString()) : new JValue(low); } offers.Add(item); } if (meta["numItemsPerBin"] is JArray) { var sorted = offers.OfType().OrderByDescending(x => int.Parse(x.RequiredString("Bin")[4..])).ToArray(); offers.Clear(); foreach (var item in sorted) offers.Add(item); } cached["Expiry"] = Wire.Date(offers.Count == 0 ? now + WorldData.Hour : offers.Min(x => Wire.DateMs(x["Expiry"]))); cursor += WorldData.Hour; } var result = (JObject)cached.DeepClone(); foreach (var offer in result.Array("ItemManifest").OfType().ToArray()) { offer.Remove("_key"); if (build < GameVersion.Of("42.0.0") && offer.Value("StoreItem") == "/Lotus/StoreItems/Weapons/Infested/InfestedLich/LongGuns/CodaBubonico/CodaBubonicoCannon") { offer.Remove(); continue; } if (inventory is not null && offer.Value("Affiliation") is string tag && offer.Value("ReductionPerPositiveRank") != 0 && offer.Value("IncreasePerNegativeRank") != 0) { var title = inventory.Array("Affiliations").FirstOrDefault(x => x.Value("Tag") == tag)?.Value("Title") ?? 0; var factor = 1 - (title < 0 ? offer.Value("IncreasePerNegativeRank") : offer.Value("ReductionPerPositiveRank")) * title; if (factor == 0) continue; if (offer["RegularPrice"] is JArray regular) { offer["RegularPriceBeforeDiscount"] = regular.DeepClone(); offer["RegularPrice"] = new JArray(regular.Select(x => (long)(x.Value() * factor))); } if (offer["ItemPrices"] is JArray prices) { offer["ItemPricesBeforeDiscount"] = prices.DeepClone(); foreach (var price in prices) price["ItemCount"] = (long)(price.Value("ItemCount") * factor); } } } return result; } }