using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed class RelicApi(ItemCatalog catalog, TimeProvider clock)
{
public static readonly HashSet<string> Controllers = ["projectionManagerController", "getVoidProjectionRewardsController"];
private static readonly string[] Qualities = ["VPQ_BRONZE", "VPQ_SILVER", "VPQ_GOLD", "VPQ_PLATINUM"];
private static readonly int[] Costs = [0, 25, 50, 100];
private static readonly double[][] Weights = [[.76, .22, .02], [.70, .26, .04], [.60, .34, .06], [.50, .40, .10]];
public ApiResponse Handle(string controller, JObject account, ApiRequest request)
{
var body = request.ObjectBody(); var inv = account.Obj("Inventory");
if (controller == "projectionManagerController")
{
var previous = body.RequiredString("projectionType"); var meta = Metadata(previous); var quality = (int)body.Integer("qualityTag", 0, 3); var old = Array.IndexOf(Qualities, meta.Value<string>("quality"));
if (old < 0 || quality <= old) throw new ApiException(400, "Relics can only be refined to a higher quality");
var next = GameData.Table("Relics").Properties().FirstOrDefault(x => x.Value.Value<string>("era") == meta.Value<string>("era") && x.Value.Value<string>("category") == meta.Value<string>("category") && x.Value.Value<string>("quality") == Qualities[quality])?.Name ?? throw new ApiException(400, "Refined relic is not available");
var cost = inv.Value<bool>("dontSubtractVoidTraces") ? 0 : Costs[quality] - Costs[old];
Inventory.AddCount(inv, "MiscItems", previous, -1); Inventory.AddCount(inv, "MiscItems", next, 1); Inventory.AddCount(inv, "MiscItems", "/Lotus/Types/Items/MiscItems/VoidTearDrop", -cost);
return ApiResponse.Json(new JObject { ["prevProjection"] = previous, ["upgradedProjection"] = next, ["upgradeCost"] = cost });
}
var wave = body["CurrentWave"]?.Value<int>() ?? body["VoidTearParticipantsCurrWave"]?.Value<int>("Wave") ?? throw new ApiException(400, "Missing relic wave");
if (wave is < 1 or > 1000) throw new ApiException(400, "Invalid relic wave");
var participant = body["ParticipantInfo"] as JObject ?? (body["VoidTearParticipantsCurrWave"]?["Participants"] as JArray)?.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["AccountId"]) == account.Value<string>("id")) ?? throw new ApiException(400, "Missing own relic participant");
if (Wire.Id(participant["AccountId"]) != account.Value<string>("id")) throw new ApiException(403, "Relic participant does not match authenticated account");
if (participant.Value<bool>("QualifiesForReward") && !participant.Value<bool>("HaveRewardResponse") && string.IsNullOrEmpty(participant.Value<string>("Reward"))) Roll(account, participant, wave, body.Value<string>("VoidProjectionRemovalHash"));
if (body["VoidTearParticipantsPrevWave"] is JObject previousWave) CorrectSelection(account, previousWave);
return ApiResponse.Json(body["CurrentWave"] is not null ? new JObject { ["CurrentWave"] = wave, ["ParticipantInfo"] = participant.DeepClone(), ["DifficultyTier"] = body.Value<int>("DifficultyTier") } : new JObject { ["VoidTearParticipantsCurrWave"] = body["VoidTearParticipantsCurrWave"]!.DeepClone() });
}
private static JObject Metadata(string type) => GameData.Find("Relics", type) ?? throw new ApiException(400, "Unknown relic");
private static JArray Pool(string relic) => GameData.Table("Rewards")[Metadata(relic).Value<string>("rewardManifest")!]?[0] as JArray ?? throw new ApiException(400, "Missing relic reward pool");
public JObject Roll(JObject account, JObject participant, int wave, string? hash = null)
{
var inv = account.Obj("Inventory"); var type = participant.RequiredString("VoidProjection"); var meta = Metadata(type);
var group = hash ?? inv["RewardSeed"]?.ToString() ?? ""; var receipts = account.Array("RelicRolls");
var receipt = receipts.OfType<JObject>().FirstOrDefault(x => x.Value<string>("group") == group && x.Value<int>("wave") == wave);
JObject reward;
if (receipt is not null)
{
if (receipt.Value<string>("relic") != type) throw new ApiException(409, "This relic wave has already been resolved");
reward = (JObject)receipt["reward"]!.DeepClone();
}
else
{
var quality = Array.IndexOf(Qualities, meta.Value<string>("quality")); if (quality < 0) throw new ApiException(400, "Invalid relic quality");
var weights = Weights[quality].ToArray();
if (quality == 1 && inv.Value<bool>("exceptionalRelicsAlwaysGiveBronzeReward")) weights = [1, 0, 0];
else if (quality == 2 && inv.Value<bool>("flawlessRelicsAlwaysGiveSilverReward")) weights = [0, 1, 0];
else if (quality == 3 && inv.Value<bool>("radiantRelicsAlwaysGiveGoldReward")) weights = [0, 0, 1];
var pool = (JArray)Pool(type).DeepClone(); var rarities = new[] { "COMMON", "UNCOMMON", "RARE" };
for (var i = 0; i < rarities.Length; i++)
{
var entries = pool.OfType<JObject>().Where(x => x.Value<string>("rarity") == rarities[i]).ToArray();
foreach (var entry in entries) entry["probability"] = weights[i] / entries.Length;
}
reward = (JObject)(SeededRng.RewardAt(pool, Random.Shared.NextDouble()) ?? throw new ApiException(400, "Empty relic pool")).DeepClone();
var count = checked(reward.Value<int>("itemCount") * Math.Clamp(inv.Value<int?>("relicRewardItemCountMultiplier") ?? 1, 1, 1000)); reward["itemCount"] = count;
Inventory.AddCount(inv, "MiscItems", type, -1); new ItemAcquisition(catalog, clock, account).Add(inv, reward.Value<string>("type")!, count);
var bonusKey = reward.Value<string>("rarity") switch { "COMMON" => "relicPlatinumBonusCommon", "UNCOMMON" => "relicPlatinumBonusUncommon", _ => "relicPlatinumBonusRare" };
var bonus = checked((inv.Value<long?>(bonusKey) ?? 0) * (inv.Value<int?>("relicRewardItemCountMultiplier") ?? 1));
if (bonus > 0) inv["pendingPremiumCredits"] = checked(inv.Value<long>("pendingPremiumCredits") + bonus);
if (wave == 1) inv["MissionRelicRewards"] = new JArray();
var missionRewards = inv.Array("MissionRelicRewards"); while (missionRewards.Count < wave) missionRewards.Add(JValue.CreateNull());
missionRewards[wave - 1] = new JObject { ["ItemType"] = reward["type"]!.DeepClone(), ["ItemCount"] = count };
receipts.Add(new JObject { ["group"] = group, ["wave"] = wave, ["relic"] = type, ["reward"] = reward.DeepClone() });
while (receipts.Count > 1000) receipts.RemoveAt(0);
}
participant["Reward"] = reward["type"]!.DeepClone(); participant["ChosenRewardOwner"] = participant["AccountId"]!.DeepClone(); return reward;
}
public void CorrectSelection(JObject account, JObject wave)
{
var inv = account.Obj("Inventory"); var index = (int)wave.Integer("Wave", 1, 1000) - 1;
if (inv["MissionRelicRewards"] is not JArray rewards || index >= rewards.Count || rewards[index] is not JObject previous) return;
var participants = wave["Participants"] as JArray ?? throw new ApiException(400, "Missing relic participants");
var self = participants.FirstOrDefault(x => Wire.Id(x["AccountId"]) == account.Value<string>("id")) ?? throw new ApiException(400, "Missing own relic selection");
if (self["ChosenRewardOwner"] is null) return;
var owner = participants.FirstOrDefault(x => Wire.Id(x["AccountId"]) == Wire.Id(self["ChosenRewardOwner"])) ?? throw new ApiException(400, "Selected relic participant is missing");
var selected = Pool(owner.Value<string>("VoidProjection") ?? "").FirstOrDefault(x => x.Value<string>("type") == owner.Value<string>("Reward")) ?? throw new ApiException(400, "Selected reward is not in that relic");
var type = selected.Value<string>("type")!; var count = checked(selected.Value<int>("itemCount") * Math.Clamp(inv.Value<int?>("relicRewardItemCountMultiplier") ?? 1, 1, 1000));
if (previous.Value<string>("ItemType") == type && previous.Value<int>("ItemCount") == count) return;
var oldType = catalog.ResolveType(previous.Value<string>("ItemType")!); var category = catalog.Get(oldType).Category;
if (!Inventory.CountedKeys.Contains(category)) throw new ApiException(400, "Relic reward cannot be exchanged after acquisition");
Inventory.AddCount(inv, category, oldType, -previous.Value<int>("ItemCount")); new ItemAcquisition(catalog, clock, account).Add(inv, type, count);
rewards[index] = new JObject { ["ItemType"] = type, ["ItemCount"] = count };
}
public void CompleteMission(JObject account, JObject wave, JArray destination)
{
var inv = account.Obj("Inventory"); var self = (wave["Participants"] as JArray)?.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["AccountId"]) == account.Value<string>("id"));
if (self?.Value<bool>("QualifiesForReward") != true) return;
if (!self.Value<bool>("HaveRewardResponse") && string.IsNullOrEmpty(self.Value<string>("Reward"))) Roll(account, self, (int)wave.Integer("Wave", 1, 1000));
CorrectSelection(account, wave);
foreach (var reward in (inv["MissionRelicRewards"] as JArray ?? []).OfType<JObject>()) destination.Add(new JObject { ["StoreItem"] = reward["ItemType"]!.DeepClone(), ["ItemCount"] = reward["ItemCount"]!.DeepClone() });
inv.Remove("MissionRelicRewards");
}
}
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed class RelicApi(ItemCatalog catalog, TimeProvider clock)
{
public static readonly HashSet<string> Controllers = ["projectionManagerController", "getVoidProjectionRewardsController"];
private static readonly string[] Qualities = ["VPQ_BRONZE", "VPQ_SILVER", "VPQ_GOLD", "VPQ_PLATINUM"];
private static readonly int[] Costs = [0, 25, 50, 100];
private static readonly double[][] Weights = [[.76, .22, .02], [.70, .26, .04], [.60, .34, .06], [.50, .40, .10]];
public ApiResponse Handle(string controller, JObject account, ApiRequest request)
{
var body = request.ObjectBody(); var inv = account.Obj("Inventory");
if (controller == "projectionManagerController")
{
var previous = body.RequiredString("projectionType"); var meta = Metadata(previous); var quality = (int)body.Integer("qualityTag", 0, 3); var old = Array.IndexOf(Qualities, meta.Value<string>("quality"));
if (old < 0 || quality <= old) throw new ApiException(400, "Relics can only be refined to a higher quality");
var next = GameData.Table("Relics").Properties().FirstOrDefault(x => x.Value.Value<string>("era") == meta.Value<string>("era") && x.Value.Value<string>("category") == meta.Value<string>("category") && x.Value.Value<string>("quality") == Qualities[quality])?.Name ?? throw new ApiException(400, "Refined relic is not available");
var cost = inv.Value<bool>("dontSubtractVoidTraces") ? 0 : Costs[quality] - Costs[old];
Inventory.AddCount(inv, "MiscItems", previous, -1); Inventory.AddCount(inv, "MiscItems", next, 1); Inventory.AddCount(inv, "MiscItems", "/Lotus/Types/Items/MiscItems/VoidTearDrop", -cost);
return ApiResponse.Json(new JObject { ["prevProjection"] = previous, ["upgradedProjection"] = next, ["upgradeCost"] = cost });
}
var wave = body["CurrentWave"]?.Value<int>() ?? body["VoidTearParticipantsCurrWave"]?.Value<int>("Wave") ?? throw new ApiException(400, "Missing relic wave");
if (wave is < 1 or > 1000) throw new ApiException(400, "Invalid relic wave");
var participant = body["ParticipantInfo"] as JObject ?? (body["VoidTearParticipantsCurrWave"]?["Participants"] as JArray)?.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["AccountId"]) == account.Value<string>("id")) ?? throw new ApiException(400, "Missing own relic participant");
if (Wire.Id(participant["AccountId"]) != account.Value<string>("id")) throw new ApiException(403, "Relic participant does not match authenticated account");
if (participant.Value<bool>("QualifiesForReward") && !participant.Value<bool>("HaveRewardResponse") && string.IsNullOrEmpty(participant.Value<string>("Reward"))) Roll(account, participant, wave, body.Value<string>("VoidProjectionRemovalHash"));
if (body["VoidTearParticipantsPrevWave"] is JObject previousWave) CorrectSelection(account, previousWave);
return ApiResponse.Json(body["CurrentWave"] is not null ? new JObject { ["CurrentWave"] = wave, ["ParticipantInfo"] = participant.DeepClone(), ["DifficultyTier"] = body.Value<int>("DifficultyTier") } : new JObject { ["VoidTearParticipantsCurrWave"] = body["VoidTearParticipantsCurrWave"]!.DeepClone() });
}
private static JObject Metadata(string type) => GameData.Find("Relics", type) ?? throw new ApiException(400, "Unknown relic");
private static JArray Pool(string relic) => GameData.Table("Rewards")[Metadata(relic).Value<string>("rewardManifest")!]?[0] as JArray ?? throw new ApiException(400, "Missing relic reward pool");
public JObject Roll(JObject account, JObject participant, int wave, string? hash = null)
{
var inv = account.Obj("Inventory"); var type = participant.RequiredString("VoidProjection"); var meta = Metadata(type);
var group = hash ?? inv["RewardSeed"]?.ToString() ?? ""; var receipts = account.Array("RelicRolls");
var receipt = receipts.OfType<JObject>().FirstOrDefault(x => x.Value<string>("group") == group && x.Value<int>("wave") == wave);
JObject reward;
if (receipt is not null)
{
if (receipt.Value<string>("relic") != type) throw new ApiException(409, "This relic wave has already been resolved");
reward = (JObject)receipt["reward"]!.DeepClone();
}
else
{
var quality = Array.IndexOf(Qualities, meta.Value<string>("quality")); if (quality < 0) throw new ApiException(400, "Invalid relic quality");
var weights = Weights[quality].ToArray();
if (quality == 1 && inv.Value<bool>("exceptionalRelicsAlwaysGiveBronzeReward")) weights = [1, 0, 0];
else if (quality == 2 && inv.Value<bool>("flawlessRelicsAlwaysGiveSilverReward")) weights = [0, 1, 0];
else if (quality == 3 && inv.Value<bool>("radiantRelicsAlwaysGiveGoldReward")) weights = [0, 0, 1];
var pool = (JArray)Pool(type).DeepClone(); var rarities = new[] { "COMMON", "UNCOMMON", "RARE" };
for (var i = 0; i < rarities.Length; i++)
{
var entries = pool.OfType<JObject>().Where(x => x.Value<string>("rarity") == rarities[i]).ToArray();
foreach (var entry in entries) entry["probability"] = weights[i] / entries.Length;
}
reward = (JObject)(SeededRng.RewardAt(pool, Random.Shared.NextDouble()) ?? throw new ApiException(400, "Empty relic pool")).DeepClone();
var count = checked(reward.Value<int>("itemCount") * Math.Clamp(inv.Value<int?>("relicRewardItemCountMultiplier") ?? 1, 1, 1000)); reward["itemCount"] = count;
Inventory.AddCount(inv, "MiscItems", type, -1); new ItemAcquisition(catalog, clock, account).Add(inv, reward.Value<string>("type")!, count);
var bonusKey = reward.Value<string>("rarity") switch { "COMMON" => "relicPlatinumBonusCommon", "UNCOMMON" => "relicPlatinumBonusUncommon", _ => "relicPlatinumBonusRare" };
var bonus = checked((inv.Value<long?>(bonusKey) ?? 0) * (inv.Value<int?>("relicRewardItemCountMultiplier") ?? 1));
if (bonus > 0) inv["pendingPremiumCredits"] = checked(inv.Value<long>("pendingPremiumCredits") + bonus);
if (wave == 1) inv["MissionRelicRewards"] = new JArray();
var missionRewards = inv.Array("MissionRelicRewards"); while (missionRewards.Count < wave) missionRewards.Add(JValue.CreateNull());
missionRewards[wave - 1] = new JObject { ["ItemType"] = reward["type"]!.DeepClone(), ["ItemCount"] = count };
receipts.Add(new JObject { ["group"] = group, ["wave"] = wave, ["relic"] = type, ["reward"] = reward.DeepClone() });
while (receipts.Count > 1000) receipts.RemoveAt(0);
}
participant["Reward"] = reward["type"]!.DeepClone(); participant["ChosenRewardOwner"] = participant["AccountId"]!.DeepClone(); return reward;
}
public void CorrectSelection(JObject account, JObject wave)
{
var inv = account.Obj("Inventory"); var index = (int)wave.Integer("Wave", 1, 1000) - 1;
if (inv["MissionRelicRewards"] is not JArray rewards || index >= rewards.Count || rewards[index] is not JObject previous) return;
var participants = wave["Participants"] as JArray ?? throw new ApiException(400, "Missing relic participants");
var self = participants.FirstOrDefault(x => Wire.Id(x["AccountId"]) == account.Value<string>("id")) ?? throw new ApiException(400, "Missing own relic selection");
if (self["ChosenRewardOwner"] is null) return;
var owner = participants.FirstOrDefault(x => Wire.Id(x["AccountId"]) == Wire.Id(self["ChosenRewardOwner"])) ?? throw new ApiException(400, "Selected relic participant is missing");
var selected = Pool(owner.Value<string>("VoidProjection") ?? "").FirstOrDefault(x => x.Value<string>("type") == owner.Value<string>("Reward")) ?? throw new ApiException(400, "Selected reward is not in that relic");
var type = selected.Value<string>("type")!; var count = checked(selected.Value<int>("itemCount") * Math.Clamp(inv.Value<int?>("relicRewardItemCountMultiplier") ?? 1, 1, 1000));
if (previous.Value<string>("ItemType") == type && previous.Value<int>("ItemCount") == count) return;
var oldType = catalog.ResolveType(previous.Value<string>("ItemType")!); var category = catalog.Get(oldType).Category;
if (!Inventory.CountedKeys.Contains(category)) throw new ApiException(400, "Relic reward cannot be exchanged after acquisition");
Inventory.AddCount(inv, category, oldType, -previous.Value<int>("ItemCount")); new ItemAcquisition(catalog, clock, account).Add(inv, type, count);
rewards[index] = new JObject { ["ItemType"] = type, ["ItemCount"] = count };
}
public void CompleteMission(JObject account, JObject wave, JArray destination)
{
var inv = account.Obj("Inventory"); var self = (wave["Participants"] as JArray)?.OfType<JObject>().FirstOrDefault(x => Wire.Id(x["AccountId"]) == account.Value<string>("id"));
if (self?.Value<bool>("QualifiesForReward") != true) return;
if (!self.Value<bool>("HaveRewardResponse") && string.IsNullOrEmpty(self.Value<string>("Reward"))) Roll(account, self, (int)wave.Integer("Wave", 1, 1000));
CorrectSelection(account, wave);
foreach (var reward in (inv["MissionRelicRewards"] as JArray ?? []).OfType<JObject>()) destination.Add(new JObject { ["StoreItem"] = reward["ItemType"]!.DeepClone(), ["ItemCount"] = reward["ItemCount"]!.DeepClone() });
inv.Remove("MissionRelicRewards");
}
}