Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of OttoPay v1.6.9
OttoPay.dll
Decompiled 2 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using OttoPay.Banking; using OttoPay.Compatibility; using OttoPay.UI; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("OttoPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("potto007")] [assembly: AssemblyProduct("OttoPay")] [assembly: AssemblyCopyright("Copyright © 2024-2026 OttoPay contributors")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: AssemblyFileVersion("1.6.9")] [assembly: InternalsVisibleTo("OttoPay.Tests")] [assembly: IgnoresAccessChecksTo("assembly_guiutils")] [assembly: IgnoresAccessChecksTo("assembly_utils")] [assembly: IgnoresAccessChecksTo("assembly_valheim")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.6.9.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace OttoPay { internal static class Constants { internal const string CoinPocketUIName = "CoinPocketUI"; internal const string ExtractCoinsButtonName = "ExtractCoinsButton"; internal const string AuraPayButtonName = "AuraPayToggleButton"; internal const string ArmorName = "Armor"; internal const string WeightName = "Weight"; internal const string JewelcraftingSynergyName = "Jewelcrafting Synergy"; internal const string TrashButtonName = "Trash"; internal const string CoinCountCustomData = "CoinPocket_CoinCount"; internal const string CoinToken = "$item_coins"; internal const string CoinsPrefabName = "Coins"; internal const string AcText = "ac_text"; internal const string ArmorIconName = "armor_icon"; internal const string QuickStackStoreGuid = "goldenrevolver.quick_stack_store"; internal const string JewelcraftingGuid = "org.bepinex.plugins.jewelcrafting"; internal const string RapidLoadoutsGuid = "Azumatt.RapidLoadouts"; internal const string OttoAuraGuid = "potto007.OttoAura"; internal const string ExtraSlotsGuid = "shudnal.ExtraSlots"; } internal static class Log { private static readonly ManualLogSource Source = Logger.CreateLogSource("OttoPay"); internal static void Debug(string message) { Source.LogDebug((object)message); } internal static void Info(string message) { Source.LogInfo((object)message); } internal static void Warning(string message) { Source.LogWarning((object)message); } internal static void Error(string message) { Source.LogError((object)message); } } public static class OttoPayApi { public const string AuraPayCustomData = "OttoPay_AuraPay"; public const string BankMemberCustomData = "OttoPay_BankMember"; public static void RegisterAuraService(string name, Func<string> describe) { AuraServices.Shared.Register(name, describe); BalancePanel.RefreshAuraPayToggle(); } public static void UnregisterAuraService(string name) { AuraServices.Shared.Unregister(name); BalancePanel.RefreshAuraPayToggle(); } public static void RegisterDepositHandler(string name, Func<Inventory, ItemData, int, bool> canDeposit, Func<Inventory, ItemData, int, bool> deposit, Func<Inventory, ItemData, int, string> describe) { DepositHandlers.Shared.Register(name, canDeposit, deposit, describe); } public static void UnregisterDepositHandler(string name) { DepositHandlers.Shared.Unregister(name); } public static bool IsBankMember() { return Membership.LocalIsMember(); } public static void JoinBank() { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { Membership.Join(localPlayer.m_customData); BalancePanel.Refresh(); } } public static int GetPouchCoins() { return Balance.Local(); } public static bool IsAuraPayEnabled() { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { return Membership.IsAuraPayOn(localPlayer.m_customData); } return false; } public static void SetAuraPayEnabled(bool enabled) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { Membership.SetAuraPay(localPlayer.m_customData, enabled); BalancePanel.RefreshAuraPayToggle(); } } public static bool TryDeposit(int amount) { if (amount < 0 || !IsBankMember()) { return false; } if (!Balance.TryDeposit(Balance.Local(), amount, out var updated)) { return false; } if (amount == 0) { return true; } Balance.SetLocal(updated); BalancePanel.Refresh(); return true; } public static bool TryWithdraw(int amount) { if (amount <= 0) { return true; } if (!IsBankMember()) { return false; } if (!Balance.TryWithdraw(Balance.Local(), amount, out var updated)) { return false; } Balance.SetLocal(updated); BalancePanel.Refresh(); return true; } } [BepInPlugin("potto007.OttoPay", "OttoPay", "1.6.9")] [BepInIncompatibility("Azumatt.CurrencyPocket")] public class OttoPayPlugin : BaseUnityPlugin { public enum Toggle { On = 1, Off = 0 } internal const string ModName = "OttoPay"; internal const string ModVersion = "1.6.9"; internal const string Author = "potto007"; private const string ModGUID = "potto007.OttoPay"; private const string ConfigFileName = "potto007.OttoPay.cfg"; private const long ReloadDelay = 10000000L; private static readonly string ConfigFileFullPath; private static readonly ConfigSync ConfigSync; private readonly Harmony _harmony = new Harmony("potto007.OttoPay"); private readonly object _reloadLock = new object(); private FileSystemWatcher? _watcher; private DateTime _lastConfigReloadTime; private static ConfigEntry<Toggle> _serverConfigLocked; public void Awake() { bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; _serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); SetupWatcher(); BalanceDropTarget.DepositSprite = EmbeddedSprites.Load("download.png"); ((BaseUnityPlugin)this).Config.Save(); if (saveOnConfigSet) { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } } public void Start() { RapidLoadoutsCompat.Init(_harmony); ExtraSlotsCompat.Init(); } private void OnDestroy() { SaveWithRespectToConfigSet(); _watcher?.Dispose(); } private void SetupWatcher() { _watcher = new FileSystemWatcher(Paths.ConfigPath, "potto007.OttoPay.cfg"); _watcher.Changed += ReadConfigValues; _watcher.Created += ReadConfigValues; _watcher.Renamed += ReadConfigValues; _watcher.IncludeSubdirectories = true; _watcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; _watcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { DateTime now = DateTime.Now; if (now.Ticks - _lastConfigReloadTime.Ticks < 10000000) { return; } lock (_reloadLock) { if (!File.Exists(ConfigFileFullPath)) { Log.Warning("Config file does not exist. Skipping reload."); return; } try { Log.Debug("Reloading configuration..."); SaveWithRespectToConfigSet(reload: true); Log.Info("Configuration reload complete."); } catch (Exception ex) { Log.Error("Error reloading configuration: " + ex.Message); } } _lastConfigReloadTime = now; } private void SaveWithRespectToConfigSet(bool reload = false) { bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; if (reload) { ((BaseUnityPlugin)this).Config.Reload(); } ((BaseUnityPlugin)this).Config.Save(); if (saveOnConfigSet) { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } } private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val); ConfigSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } static OttoPayPlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + "potto007.OttoPay.cfg"; ConfigSync = new ConfigSync("potto007.OttoPay") { DisplayName = "OttoPay", CurrentVersion = "1.6.9", MinimumRequiredVersion = "1.6.9", ModRequired = false }; _serverConfigLocked = null; } } } namespace OttoPay.UI { internal sealed class BalanceDropTarget : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerMoveHandler, IPointerExitHandler, IPointerClickHandler { private const string TooltipHostName = "OttoPayBalanceTooltip"; internal static Sprite? DepositSprite; private UITooltip? _tooltip; private Image? _icon; private Material? _iconMaterial; private void Awake() { TryCreateTooltip(); _icon = ((Component)((Component)this).transform.Find("armor_icon")).GetComponent<Image>(); _iconMaterial = ((Graphic)_icon).material; } private void Update() { if ((Object)(object)_icon == (Object)null) { return; } ItemData val = DraggedItem(); if (val == null || (!IsCoin(val) && HandlerFor(val) == null)) { if ((Object)(object)_icon.sprite != (Object)(object)BalancePanel.CoinSprite) { _icon.sprite = BalancePanel.CoinSprite; ((Graphic)_icon).material = _iconMaterial; } } else if (!((Object)(object)_icon.sprite == (Object)(object)DepositSprite)) { _icon.sprite = DepositSprite; ((Graphic)_icon).material = null; } } public void OnPointerEnter(PointerEventData eventData) { if (!OverChildButton(eventData)) { ShowBalanceTooltip(eventData.pointerEnter); } } public void OnPointerMove(PointerEventData eventData) { if (!((Object)(object)UITooltip.m_current != (Object)null) && !OverChildButton(eventData)) { ShowBalanceTooltip(eventData.pointerEnter); } } public void OnPointerExit(PointerEventData eventData) { if ((Object)(object)_tooltip != (Object)null && (Object)(object)UITooltip.m_current == (Object)(object)_tooltip) { UITooltip.HideTooltip(); } } public void OnPointerClick(PointerEventData eventData) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) InventoryGui instance = InventoryGui.m_instance; if (!((Object)(object)instance == (Object)null) && (int)eventData.button == 0 && !((Object)(object)instance.m_dragGo == (Object)null) && instance.m_dragItem != null && instance.m_dragInventory != null) { ItemData dragItem = instance.m_dragItem; if (IsCoin(dragItem)) { DepositCoins(instance, dragItem); } else if (!DepositWithHandler(instance, dragItem)) { return; } BalancePanel.Refresh(); instance.SetupDragItem((ItemData)null, (Inventory)null, 1); } } private static void DepositCoins(InventoryGui gui, ItemData coins) { Balance.SetLocal(Balance.Local() + gui.m_dragAmount); if (gui.m_dragAmount == coins.m_stack) { gui.m_dragInventory.RemoveItem(coins); } else { gui.m_dragInventory.RemoveItem(coins, gui.m_dragAmount); } } private static bool DepositWithHandler(InventoryGui gui, ItemData item) { return HandlerFor(item)?.Deposit(gui.m_dragInventory, item, gui.m_dragAmount) ?? false; } private bool OverChildButton(PointerEventData eventData) { GameObject pointerEnter = eventData.pointerEnter; if ((Object)(object)pointerEnter == (Object)null) { return false; } Button componentInParent = pointerEnter.GetComponentInParent<Button>(); if ((Object)(object)componentInParent != (Object)null && (Object)(object)((Component)componentInParent).transform != (Object)(object)((Component)this).transform) { return ((Component)componentInParent).transform.IsChildOf(((Component)this).transform); } return false; } private void ShowBalanceTooltip(GameObject? hovered) { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) TryCreateTooltip(); InventoryGui instance = InventoryGui.m_instance; if (!((Object)(object)instance == (Object)null) && !((Object)(object)_tooltip == (Object)null)) { ItemData val = DraggedItem(); DepositHandler depositHandler = ((val != null) ? HandlerFor(val) : null); if (val != null && IsCoin(val)) { _tooltip.Set("Deposit coins", "Click to deposit these coins in your Merchant Bank balance.", (RectTransform)null, default(Vector2)); } else if (val != null && depositHandler != null) { _tooltip.Set(depositHandler.Name, depositHandler.Describe(instance.m_dragInventory, val, instance.m_dragAmount), (RectTransform)null, default(Vector2)); } else { _tooltip.Set("Merchant Bank", $"Balance: {Balance.Local()} coins.\n\nDrop coins here to deposit them. Any merchant draws on your balance when you buy.", (RectTransform)null, default(Vector2)); } _tooltip.OnHoverStart((GameObject)(((Object)(object)hovered != (Object)null) ? ((object)hovered) : ((object)((Component)this).gameObject))); } } private static ItemData? DraggedItem() { InventoryGui instance = InventoryGui.m_instance; if (!((Object)(object)instance != (Object)null) || !((Object)(object)instance.m_dragGo != (Object)null)) { return null; } return instance.m_dragItem; } private static bool IsCoin(ItemData item) { return item.m_shared.m_name == "$item_coins"; } private static DepositHandler? HandlerFor(ItemData item) { InventoryGui instance = InventoryGui.m_instance; Inventory val = (((Object)(object)instance != (Object)null) ? instance.m_dragInventory : null); if ((Object)(object)instance == (Object)null || val == null || IsCoin(item)) { return null; } return DepositHandlers.Shared.Accepting(val, item, instance.m_dragAmount); } private void TryCreateTooltip() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown if (!((Object)(object)_tooltip != (Object)null)) { GameObject val = new GameObject("OttoPayBalanceTooltip", new Type[1] { typeof(RectTransform) }); val.transform.SetParent(((Component)this).transform, false); _tooltip = Tooltips.Attach(val, "", ""); if ((Object)(object)_tooltip == (Object)null) { Object.Destroy((Object)(object)val); } } } } internal static class BalancePanel { [CompilerGenerated] private static class <>O { public static UnityAction <0>__Start; public static UnityAction <1>__ToggleAuraPay; } private static GameObject? _panel; private static Button? _withdrawButton; private static Button? _auraPayButton; private static GameObject? _shiftedFor; private static Coroutine? _shift; internal static Sprite? CoinSprite; internal static void Build(InventoryGui gui) { if ((Object)(object)_panel == (Object)null) { CreatePanel(gui); } if ((Object)(object)_withdrawButton == (Object)null && (Object)(object)_panel != (Object)null) { CreateWithdrawButton(gui, _panel); } if ((Object)(object)_auraPayButton == (Object)null && (Object)(object)_panel != (Object)null && Chainloader.PluginInfos.ContainsKey("potto007.OttoAura")) { CreateAuraPayToggle(gui, _panel); } } internal static void Refresh() { if ((Object)(object)_panel == (Object)null) { return; } _panel.SetActive(Membership.LocalIsMember()); Transform val = Utils.FindChild(_panel.transform, "ac_text", (IterativeSearchType)0); if (!((Object)(object)val == (Object)null)) { TextMeshProUGUI component = ((Component)val).GetComponent<TextMeshProUGUI>(); if (!((Object)(object)component == (Object)null)) { ((TMP_Text)component).text = $"{Balance.Local()}"; AttachWithdrawTooltip(); RefreshAuraPayToggle(); } } } internal static void RefreshAuraPayToggle() { if (!((Object)(object)_auraPayButton == (Object)null)) { TextMeshProUGUI componentInChildren = ((Component)_auraPayButton).GetComponentInChildren<TextMeshProUGUI>(); if (!((Object)(object)componentInChildren == (Object)null)) { ((TMP_Text)componentInChildren).textWrappingMode = (TextWrappingModes)0; ((TMP_Text)componentInChildren).overflowMode = (TextOverflowModes)0; ((TMP_Text)componentInChildren).enableAutoSizing = true; ((TMP_Text)componentInChildren).fontSizeMin = 8f; bool flag = OttoPayApi.IsAuraPayEnabled(); ((TMP_Text)componentInChildren).text = (flag ? "<color=#7CFFB2>AuraPay</color>" : "<color=#8A8A8A>AuraPay</color>"); IReadOnlyList<string> readOnlyList = AuraServices.Shared.Lines(); string text = ((readOnlyList.Count > 0) ? ("\n\n" + string.Join("\n\n", readOnlyList)) : ""); Tooltips.Attach(((Component)_auraPayButton).gameObject, "AuraPay", flag ? ("AuraPay is on.\n\nA ward aura may charge your Merchant Bank balance to repair the gear you are wearing." + text + "\n\nClick to turn it off.") : ("AuraPay is off.\n\nWard auras will not charge your Merchant Bank balance for repairs." + text + "\n\nClick to turn it on.")); } } } internal static void MakeRoom(InventoryGui gui) { if (!Membership.LocalIsMember()) { return; } if ((Object)(object)_shiftedFor != (Object)null) { if (_shift != null) { ((MonoBehaviour)gui).StopCoroutine(_shift); } } else { _shiftedFor = ((Component)gui).gameObject; _shift = ((MonoBehaviour)gui).StartCoroutine(ShiftPanelsNextFrame(gui)); } } internal static bool OverlappingPanelModInstalled() { Dictionary<string, PluginInfo> pluginInfos = Chainloader.PluginInfos; if (!pluginInfos.ContainsKey("goldenrevolver.quick_stack_store")) { return pluginInfos.ContainsKey("org.bepinex.plugins.jewelcrafting"); } return true; } private static IEnumerator ShiftPanelsNextFrame(InventoryGui gui) { yield return null; Transform transform = ((Component)gui.m_player).transform; int num = 0; while (num < transform.childCount) { Transform child = transform.GetChild(num); bool flag; switch (((Object)child).name) { case "Armor": case "Weight": case "Jewelcrafting Synergy": case "CoinPocketUI": case "Trash": flag = true; break; default: flag = false; break; } RectTransform component; if (flag) { component = ((Component)child).gameObject.GetComponent<RectTransform>(); if ((Object)(object)component != (Object)null) { string name = ((Object)child).name; if (!(name == "CoinPocketUI")) { if (!(name == "Weight") || OverlappingPanelModInstalled()) { goto IL_0119; } } else { if (OverlappingPanelModInstalled()) { goto IL_0119; } component.anchoredPosition += new Vector2(0f, -45f); } } } goto IL_013a; IL_013a: if (((Object)child).name == "selected_frame") { ((Component)((Component)child).transform.Find("selected (2)")).gameObject.SetActive(false); ((Component)((Component)child).transform.Find("selected (3)")).gameObject.SetActive(false); } num++; continue; IL_0119: component.anchoredPosition += new Vector2(0f, 45f); goto IL_013a; } } private static void CreatePanel(InventoryGui gui) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) Transform transform = ((Component)gui.m_player).transform; Transform val = transform.Find("Armor"); GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, transform); ((Object)val2).name = "CoinPocketUI"; RectTransform component = val2.GetComponent<RectTransform>(); Log.Debug($"Creating pocket UI at {component.anchoredPosition}"); if (OverlappingPanelModInstalled()) { component.anchoredPosition += new Vector2(0f, -234f); } else { RectTransform component2 = ((Component)val).GetComponent<RectTransform>(); RectTransform component3 = ((Component)transform.Find("Weight")).GetComponent<RectTransform>(); val2.transform.SetSiblingIndex(val.GetSiblingIndex()); component.anchoredPosition = new Vector2(component2.anchoredPosition.x, (component2.anchoredPosition.y + component3.anchoredPosition.y) / 2f); } Log.Debug($"Creating pocket UI at {component.anchoredPosition}"); CoinSprite = ObjectDB.instance.GetItemPrefab("Coins").GetComponent<ItemDrop>().m_itemData.GetIcon(); ((Component)val2.transform.Find("armor_icon")).GetComponent<Image>().sprite = CoinSprite; val2.transform.SetSiblingIndex(val.GetSiblingIndex()); ((TMP_Text)((Component)val2.transform.Find("ac_text")).GetComponent<TextMeshProUGUI>()).text = $"{Balance.Local()}"; Tooltips.Strip(val2); val2.AddComponent<BalanceDropTarget>(); _panel = val2; } private static void CreateWithdrawButton(InventoryGui gui, GameObject panel) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) Button val = Object.Instantiate<Button>(gui.m_takeAllButton, panel.transform); ((Object)val).name = "ExtractCoinsButton"; ((TMP_Text)((Component)val).GetComponentInChildren<TextMeshProUGUI>()).text = "\ud83d\udce6"; ((Component)val).transform.SetParent(panel.transform, false); val.onClick = new ButtonClickedEvent(); ButtonClickedEvent onClick = val.onClick; object obj = <>O.<0>__Start; if (obj == null) { UnityAction val2 = Withdrawal.Start; <>O.<0>__Start = val2; obj = (object)val2; } ((UnityEvent)onClick).AddListener((UnityAction)obj); DetachGamepadHint(val); RectTransform val3 = ((Component)val).GetComponent<RectTransform>(); if ((Object)(object)val3 == (Object)null) { val3 = ((Component)val).gameObject.AddComponent<RectTransform>(); } ((Transform)val3).localPosition = new Vector3(2.5f, -20f, 0f); ((Component)val).transform.localScale = new Vector3(0.4f, 0.4f, 1f); Tooltips.Strip(((Component)val).gameObject); _withdrawButton = val; AttachWithdrawTooltip(); } private static void CreateAuraPayToggle(InventoryGui gui, GameObject panel) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown Button obj = Object.Instantiate<Button>(gui.m_takeAllButton, panel.transform); ((Object)obj).name = "AuraPayToggleButton"; ((Component)obj).transform.SetParent(panel.transform, false); Tooltips.Strip(((Component)obj).gameObject); obj.onClick = new ButtonClickedEvent(); ButtonClickedEvent onClick = obj.onClick; object obj2 = <>O.<1>__ToggleAuraPay; if (obj2 == null) { UnityAction val = ToggleAuraPay; <>O.<1>__ToggleAuraPay = val; obj2 = (object)val; } ((UnityEvent)onClick).AddListener((UnityAction)obj2); DetachGamepadHint(obj); ((Transform)((Component)obj).GetComponent<RectTransform>()).localPosition = new Vector3(2.5f, -38f, 0f); ((Component)obj).transform.localScale = new Vector3(0.4f, 0.4f, 1f); _auraPayButton = obj; RefreshAuraPayToggle(); } private static void ToggleAuraPay() { bool flag = !OttoPayApi.IsAuraPayEnabled(); OttoPayApi.SetAuraPayEnabled(flag); Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { ((Character)localPlayer).Message((MessageType)1, flag ? "AuraPay on: ward auras may charge your Merchant Bank balance." : "AuraPay off: ward auras will not charge your balance.", 0, (Sprite)null, false); } } private static void AttachWithdrawTooltip() { if (!((Object)(object)_withdrawButton == (Object)null)) { Tooltips.Attach(((Component)_withdrawButton).gameObject, "Withdraw coins", "Take coins from your Merchant Bank balance and put them in your inventory.\n\nChoose how many in the dialog. Hold Ctrl when you click to take them all.\n\nDrop coins on your balance to deposit them again."); } } internal static void DetachGamepadHint(Button button) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) UIGamePad component = ((Component)button).GetComponent<UIGamePad>(); if (!((Object)(object)component == (Object)null)) { if ((Object)(object)component.m_hint != (Object)null) { Object.Destroy((Object)(object)component.m_hint); } component.m_hint = null; component.m_zinputKey = string.Empty; component.m_keyCode = (KeyCode)0; } } } internal static class EmbeddedSprites { private static readonly MethodInfo? LoadImageMethod = AccessTools.Method("UnityEngine.ImageConversion:LoadImage", new Type[2] { typeof(Texture2D), typeof(byte[]) }, (Type[])null); internal static Sprite Load(string name) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) Texture2D val = LoadTexture(name); if (!((Object)(object)val != (Object)null)) { return null; } return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), Vector2.zero); } private static Texture2D LoadTexture(string name) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown Texture2D val = new Texture2D(0, 0); if (LoadImageMethod == null) { Log.Error("UnityEngine.ImageConversion.LoadImage was not found. Textures will not load."); return val; } LoadImageMethod.Invoke(null, new object[2] { val, ReadBytes("assets." + name) }); return val; } private static byte[] ReadBytes(string name) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); using MemoryStream memoryStream = new MemoryStream(); executingAssembly.GetManifestResourceStream(executingAssembly.GetName().Name + "." + name).CopyTo(memoryStream); return memoryStream.ToArray(); } } internal static class JoinButton { private const string JoinButtonName = "MerchantBankJoinButton"; private const string JoinLabel = "Join Merchant Bank"; private static Button? _button; private static GameObject? _message; internal static void Refresh(StoreGui gui) { if ((Object)(object)_button == (Object)null) { Create(gui); } if ((Object)(object)_button != (Object)null) { ((Component)_button).gameObject.SetActive(!Membership.LocalIsMember()); } } private static void Create(StoreGui gui) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Unknown result type (might be due to invalid IL or missing references) //IL_033e: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)gui.m_buyButton == (Object)null) && !((Object)(object)gui.m_sellButton == (Object)null)) { Button val = Object.Instantiate<Button>(gui.m_buyButton, ((Component)gui.m_sellButton).transform.parent); ((Object)val).name = "MerchantBankJoinButton"; val.onClick = new ButtonClickedEvent(); ((UnityEvent)val.onClick).AddListener((UnityAction)delegate { Join(gui); }); ((Selectable)val).interactable = true; BalancePanel.DetachGamepadHint(val); Localize[] componentsInChildren = ((Component)val).GetComponentsInChildren<Localize>(true); for (int num = 0; num < componentsInChildren.Length; num++) { Object.Destroy((Object)(object)componentsInChildren[num]); } TextMeshProUGUI[] componentsInChildren2 = ((Component)val).GetComponentsInChildren<TextMeshProUGUI>(true); TextMeshProUGUI[] array = componentsInChildren2; foreach (TextMeshProUGUI obj in array) { ((TMP_Text)obj).text = "Join Merchant Bank"; ((TMP_Text)obj).textWrappingMode = (TextWrappingModes)0; ((TMP_Text)obj).overflowMode = (TextOverflowModes)0; ((TMP_Text)obj).enableAutoSizing = true; ((TMP_Text)obj).fontSizeMin = 9f; } RectTransform component = ((Component)gui.m_sellButton).GetComponent<RectTransform>(); RectTransform component2 = ((Component)gui.m_buyButton).GetComponent<RectTransform>(); RectTransform component3 = ((Component)val).GetComponent<RectTransform>(); Rect rect = component2.rect; float num2 = Mathf.Max(((Rect)(ref rect)).width, 210f); rect = component.rect; Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(num2, Mathf.Max(((Rect)(ref rect)).height, 36f)); component3.anchorMin = component.anchorMin; component3.anchorMax = component.anchorMax; component3.pivot = component.pivot; Vector2 zero = Vector2.zero; Transform parent = ((Component)val).transform.parent; RectTransform val3 = (RectTransform)(object)((parent is RectTransform) ? parent : null); if (val3 != null) { rect = val3.rect; Vector2 size = ((Rect)(ref rect)).size; ((Vector2)(ref zero))..ctor((component3.anchorMax.x - component3.anchorMin.x) * size.x, (component3.anchorMax.y - component3.anchorMin.y) * size.y); } component3.sizeDelta = val2 - zero; float x = component3.pivot.x; float x2 = val2.x; rect = component.rect; float num3 = x * (x2 - ((Rect)(ref rect)).width); Vector2 anchoredPosition = component.anchoredPosition; rect = component.rect; component3.anchoredPosition = anchoredPosition + new Vector2(num3, ((Rect)(ref rect)).height + 8f); Tooltips.Strip(((Component)val).gameObject); Tooltips.Attach(((Component)val).gameObject, "Merchant Bank", "Join the Merchant Bank Network.\n\nCoins you pick up vanish into your Merchant Bank balance, held for you by merchant magic. They take no inventory slot and weigh nothing.\n\nAny merchant draws on your balance when you buy, and you can call coins back into your hand whenever you like."); _button = val; rect = component3.rect; Vector2 size2 = ((Rect)(ref rect)).size; Log.Info($"Merchant Bank join button created at {component3.anchoredPosition}, size {size2}, wanted {val2}, labels {componentsInChildren2.Length}."); if (size2.x <= 1f || size2.y <= 1f) { Log.Warning($"Join button has a degenerate size {size2} and will not be visible. Falling back to a fixed size."); Vector2 val4 = default(Vector2); ((Vector2)(ref val4))..ctor(0.5f, 0.5f); component3.pivot = val4; Vector2 anchorMin = (component3.anchorMax = val4); component3.anchorMin = anchorMin; component3.sizeDelta = val2; } } } private static void Join(StoreGui gui) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && !Membership.IsMember(localPlayer.m_customData)) { OttoPayApi.JoinBank(); string text = (((Object)(object)gui.m_trader != (Object)null) ? Localization.instance.Localize(gui.m_trader.m_name) : "The merchant") + " binds you to the Merchant Bank Network.\nCoins you pick up now go straight to your balance."; ((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false); ShowStoreMessage(gui, text); if ((Object)(object)_button != (Object)null) { ((Component)_button).gameObject.SetActive(false); } gui.FillList(); } } private static void ShowStoreMessage(StoreGui gui, string text) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)gui.m_rootPanel == (Object)null)) { if ((Object)(object)_message != (Object)null) { Object.Destroy((Object)(object)_message); } GameObject val = new GameObject("OttoPayStoreMessage", new Type[2] { typeof(RectTransform), typeof(Image) }); val.transform.SetParent(gui.m_rootPanel.transform, false); val.transform.SetAsLastSibling(); RectTransform val2 = (RectTransform)val.transform; Vector2 val3 = default(Vector2); ((Vector2)(ref val3))..ctor(0.5f, 0.5f); val2.pivot = val3; Vector2 anchorMin = (val2.anchorMax = val3); val2.anchorMin = anchorMin; val2.sizeDelta = new Vector2(250f, 130f); val2.anchoredPosition = Vector2.zero; Image component = val.GetComponent<Image>(); ((Graphic)component).color = new Color(0.06f, 0.05f, 0.04f, 0.93f); ((Graphic)component).raycastTarget = false; GameObject val5 = new GameObject("Text", new Type[2] { typeof(RectTransform), typeof(TextMeshProUGUI) }); val5.transform.SetParent(val.transform, false); RectTransform val6 = (RectTransform)val5.transform; val6.anchorMin = Vector2.zero; val6.anchorMax = Vector2.one; val6.offsetMin = new Vector2(12f, 12f); val6.offsetMax = new Vector2(-12f, -12f); TextMeshProUGUI component2 = val5.GetComponent<TextMeshProUGUI>(); ((TMP_Text)component2).text = text; ((TMP_Text)component2).alignment = (TextAlignmentOptions)514; ((TMP_Text)component2).enableAutoSizing = true; ((TMP_Text)component2).fontSizeMin = 10f; ((TMP_Text)component2).fontSizeMax = 18f; ((Graphic)component2).raycastTarget = false; if ((Object)(object)gui.m_coinText != (Object)null) { ((TMP_Text)component2).font = gui.m_coinText.font; ((Graphic)component2).color = ((Graphic)gui.m_coinText).color; } _message = val; ((MonoBehaviour)gui).StartCoroutine(HideMessageAfter(6f)); } } private static IEnumerator HideMessageAfter(float seconds) { yield return (object)new WaitForSeconds(seconds); if (!((Object)(object)_message == (Object)null)) { Object.Destroy((Object)(object)_message); _message = null; } } } internal static class Tooltips { private static GameObject? _prefab; internal static GameObject? Prefab() { if ((Object)(object)_prefab != (Object)null) { return _prefab; } InventoryGrid val = (((Object)(object)InventoryGui.instance != (Object)null) ? InventoryGui.instance.m_playerGrid : null); if ((Object)(object)val == (Object)null) { return null; } UITooltip val2 = (((Object)(object)val.m_elementPrefab != (Object)null) ? val.m_elementPrefab.GetComponentInChildren<UITooltip>(true) : null); if ((Object)(object)val2 == (Object)null || (Object)(object)val2.m_tooltipPrefab == (Object)null) { val2 = val.m_elements.FirstOrDefault()?.m_tooltip; } if ((Object)(object)val2 == (Object)null || (Object)(object)val2.m_tooltipPrefab == (Object)null) { return null; } _prefab = val2.m_tooltipPrefab; Log.Info("Tooltips use the '" + ((Object)_prefab).name + "' prefab."); return _prefab; } internal static void Strip(GameObject root) { UITooltip[] componentsInChildren = root.GetComponentsInChildren<UITooltip>(true); foreach (UITooltip val in componentsInChildren) { Log.Info("Removed cloned tooltip on '" + ((Object)val).name + "' (prefab '" + (((Object)(object)val.m_tooltipPrefab != (Object)null) ? ((Object)val.m_tooltipPrefab).name : "none") + "')."); Object.DestroyImmediate((Object)(object)val); } } internal static UITooltip? Attach(GameObject? target, string topic, string text) { if ((Object)(object)target == (Object)null) { return null; } GameObject val = Prefab(); if ((Object)(object)val == (Object)null) { Log.Warning("No tooltip prefab found yet, so '" + topic + "' has no tooltip."); return null; } UITooltip val2 = target.GetComponent<UITooltip>(); if ((Object)(object)val2 == (Object)null) { val2 = target.AddComponent<UITooltip>(); } val2.m_tooltipPrefab = val; val2.m_topic = topic; val2.m_text = text; return val2; } } } namespace OttoPay.Patches { [HarmonyPatch] internal static class BalancePanelPatches { [HarmonyPostfix] [HarmonyAfter(new string[] { "org.bepinex.plugins.jewelcrafting" })] [HarmonyPatch(typeof(InventoryGui), "Awake")] private static void InventoryGuiAwakePostfix(InventoryGui __instance) { BalancePanel.Build(__instance); } [HarmonyPrefix] [HarmonyPatch(typeof(InventoryGui), "Show")] private static void InventoryGuiShowPrefix() { BalancePanel.Refresh(); } [HarmonyPostfix] [HarmonyPriority(100)] [HarmonyPatch(typeof(InventoryGui), "Show")] private static void InventoryGuiShowPostfix(InventoryGui __instance) { BalancePanel.MakeRoom(__instance); } } [HarmonyPatch] internal static class CoinPickupPatches { private static bool _autoPickingUp; [HarmonyPrefix] [HarmonyPriority(300)] [HarmonyPatch(typeof(Humanoid), "Pickup")] private static bool HumanoidPickupPrefix(Humanoid __instance, GameObject go, bool autoPickupDelay, bool __runOriginal, ref bool __result) { //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) if (__runOriginal) { Player val = (Player)(object)((__instance is Player) ? __instance : null); if (val != null && !((Character)val).IsTeleporting()) { ItemDrop component = go.GetComponent<ItemDrop>(); if ((Object)(object)component == (Object)null || !component.CanPickup(autoPickupDelay) || component.m_nview.GetZDO() == null) { return true; } if ((Object)(object)component.m_itemData.m_dropPrefab == (Object)null) { component.m_itemData.m_dropPrefab = ObjectDB.instance.GetItemPrefab(Utils.GetPrefabName(((Component)component).gameObject)); } _autoPickingUp = false; if (component.m_itemData.m_shared.m_name != "$item_coins" || !Membership.LocalIsMember()) { return true; } int stack = component.m_itemData.m_stack; Balance.SetLocal(Balance.Local() + stack); BalancePanel.Refresh(); ZNetScene.instance.Destroy(go); ((Humanoid)val).m_pickupEffects.Create(((Component)val).transform.position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID)); ((Character)val).ShowPickupMessage(component.m_itemData, stack); __result = true; return false; } } return true; } [HarmonyPrefix] [HarmonyPatch(typeof(Player), "AutoPickup")] private static void PlayerAutoPickupPrefix() { _autoPickingUp = true; } [HarmonyFinalizer] [HarmonyPatch(typeof(Player), "AutoPickup")] private static void PlayerAutoPickupFinalizer() { _autoPickingUp = false; } [HarmonyPostfix] [HarmonyPatch(typeof(Inventory), "CanAddItem", new Type[] { typeof(ItemData), typeof(int) })] private static void InventoryCanAddItemPostfix(ItemData item, ref bool __result) { if (!__result && _autoPickingUp && item?.m_shared?.m_name == "$item_coins" && Membership.LocalIsMember()) { __result = true; } } } [HarmonyPatch] internal static class MerchantBankPatches { [HarmonyPostfix] [HarmonyPatch(typeof(StoreGui), "Show")] private static void StoreGuiShowPostfix(StoreGui __instance) { JoinButton.Refresh(__instance); } } [HarmonyPatch] internal static class PaymentPatches { [HarmonyPostfix] [HarmonyPatch(typeof(StoreGui), "GetPlayerCoins")] private static void StoreGuiGetPlayerCoinsPostfix(ref int __result) { if (Membership.LocalIsMember()) { __result += Balance.Local(); } } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(string), typeof(int), typeof(int), typeof(bool) })] private static void InventoryRemoveItemPrefix(Inventory __instance, string name, int itemQuality, bool worldLevelBased, out int __state) { __state = ((name == "$item_coins") ? __instance.CountItems(name, itemQuality, worldLevelBased) : 0); } [HarmonyPostfix] [HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(string), typeof(int), typeof(int), typeof(bool) })] private static void InventoryRemoveItemPostfix(Inventory __instance, string name, int amount, int itemQuality, bool worldLevelBased, int __state) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && __instance == ((Humanoid)localPlayer).GetInventory() && !(name != "$item_coins") && Membership.IsMember(localPlayer.m_customData)) { int paidFromCarried = __state - __instance.CountItems(name, itemQuality, worldLevelBased); int num = Balance.Local(); int num2 = Balance.AfterPurchase(num, amount, paidFromCarried); if (num2 != num) { Balance.SetLocal(num2); BalancePanel.Refresh(); } } } } [HarmonyPatch] internal static class WithdrawalPatches { [HarmonyPrefix] [HarmonyPatch(typeof(InventoryGui), "OnSplitOk")] private static void InventoryGuiOnSplitOkPrefix(InventoryGui __instance) { Withdrawal.ConfirmSplit(__instance); } [HarmonyPrefix] [HarmonyPatch(typeof(InventoryGui), "SetupDragItem")] private static void InventoryGuiSetupDragItemPrefix(InventoryGui __instance, Inventory inventory) { if (Withdrawal.Shared.Owns(__instance.m_dragInventory) && !Withdrawal.Shared.Owns(inventory)) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && Withdrawal.Shared.DragEnded(localPlayer.m_customData) > 0) { BalancePanel.Refresh(); } } } [HarmonyPrefix] [HarmonyPatch(typeof(InventoryGui), "UpdateContainer")] private static bool InventoryGuiUpdateContainerPrefix(InventoryGui __instance) { if ((Object)(object)__instance.m_currentContainer != (Object)null && __instance.m_currentContainer.IsOwner()) { return true; } return !Withdrawal.IsWithdrawalDrag(__instance.m_dragInventory); } [HarmonyPrefix] [HarmonyPatch(typeof(InventoryGrid), "DropItem")] private static bool InventoryGridDropItemPrefix(InventoryGrid __instance, Inventory fromInventory, Vector2i pos, ref bool __result) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (!Withdrawal.Shared.Owns(fromInventory) || Withdrawal.MayLandOn(__instance.m_inventory.GetItemAt(pos.x, pos.y))) { return true; } __result = false; return false; } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[] { typeof(Inventory), typeof(ItemData), typeof(int), typeof(int), typeof(int) })] private static bool InventoryMoveItemToThisPrefix(Inventory __instance, Inventory fromInventory, ItemData item, int amount, int x, int y, ref bool __result) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return true; } if (item?.m_shared?.m_name != "$item_coins" || __instance != ((Humanoid)localPlayer).GetInventory() || !Membership.IsMember(localPlayer.m_customData)) { return true; } __result = CoinPlacement.MoveInto(__instance, fromInventory, item, amount, x, y); return false; } } } namespace OttoPay.Compatibility { internal static class ExtraSlotsCompat { private const string SectionName = "Mods compatibility - Reduced inventory size"; private static bool _handlingChange; internal static void Init() { if (Chainloader.PluginInfos.TryGetValue("shudnal.ExtraSlots", out var value)) { ConfigFile config = value.Instance.Config; if ((0u | (Watch(config, "Panels to show with 1 row", 1) ? 1u : 0u) | (Watch(config, "Panels to show with 2 rows", 2) ? 1u : 0u) | (Watch(config, "Panels to show with 3 rows", 3) ? 1u : 0u)) != 0) { config.Save(); } } } internal static bool Watch(ConfigFile config, string key, int maxPanels) { ConfigEntry<string> entry = default(ConfigEntry<string>); if (!config.TryGetEntry<string>("Mods compatibility - Reduced inventory size", key, ref entry)) { return false; } bool result = Sanitize(entry, maxPanels); entry.SettingChanged += delegate { if (_handlingChange) { return; } try { _handlingChange = true; Sanitize(entry, maxPanels); } finally { _handlingChange = false; } }; return result; } private static bool Sanitize(ConfigEntry<string> entry, int maxPanels) { string text = entry.Value ?? string.Empty; string text2 = WithoutBalancePanel(text, maxPanels); if (text2 == text) { return false; } entry.Value = text2; return true; } internal static string WithoutBalancePanel(string csv, int maxPanels) { if (string.IsNullOrWhiteSpace(csv)) { return string.Empty; } string[] array = csv.Split(new char[1] { ',' }); if (array.Count((string token) => !string.IsNullOrWhiteSpace(token)) <= maxPanels) { return csv; } List<string> list = new List<string>(array.Length); bool flag = false; string[] array2 = array; foreach (string text in array2) { if (text.Trim().Equals("CoinPocketUI", StringComparison.OrdinalIgnoreCase)) { flag = true; } else { list.Add(text); } } if (!flag) { return csv; } if (list.Count != 0) { return string.Join(",", list); } return string.Empty; } } internal static class RapidLoadoutsCompat { private const string CoinCountMethod = "RapidLoadouts.UI.PurchasableLoadoutGui:GetPlayerCoins"; internal static void Init(Harmony harmony) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown if (Chainloader.PluginInfos.TryGetValue("Azumatt.RapidLoadouts", out var value) && value != null && !((Object)(object)value.Instance == (Object)null)) { MethodInfo methodInfo = AccessTools.Method("RapidLoadouts.UI.PurchasableLoadoutGui:GetPlayerCoins", (Type[])null, (Type[])null); if (methodInfo == null) { Log.Warning("RapidLoadouts is installed but RapidLoadouts.UI.PurchasableLoadoutGui:GetPlayerCoins was not found, so its loadouts will not see the balance."); } else { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(RapidLoadoutsCompat), "PurchasableLoadoutGuiGetPlayerCoinsPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } private static void PurchasableLoadoutGuiGetPlayerCoinsPostfix(ref int __result, ItemDrop ___m_coinPrefab) { if (!((Object)(object)___m_coinPrefab == (Object)null) && !(___m_coinPrefab.m_itemData.m_shared.m_name != "$item_coins") && Membership.LocalIsMember()) { __result += Balance.Local(); } } } } namespace OttoPay.Banking { internal sealed class AuraServices { internal static readonly AuraServices Shared = new AuraServices(); private readonly List<(string Name, Func<string> Describe)> _services = new List<(string, Func<string>)>(); private readonly HashSet<string> _warnedNames = new HashSet<string>(); internal void Register(string name, Func<string> describe) { for (int i = 0; i < _services.Count; i++) { if (!(_services[i].Name != name)) { _services[i] = (name, describe); return; } } _services.Add((name, describe)); } internal void Unregister(string name) { _services.RemoveAll(((string Name, Func<string> Describe) service) => service.Name == name); } internal IReadOnlyList<string> Lines() { List<string> list = new List<string>(); foreach (var (text, func) in _services) { string text2; try { text2 = func(); } catch (Exception ex) { if (_warnedNames.Add(text)) { Log.Warning("OttoPayApi: aura service '" + text + "' describe() threw: " + ex.Message); } continue; } if (!string.IsNullOrWhiteSpace(text2)) { list.Add(text2.Trim()); } } return list; } } internal static class Balance { internal static int Read(Dictionary<string, string> customData) { if (!customData.TryGetValue("CoinPocket_CoinCount", out string value)) { return 0; } return int.Parse(value); } internal static void Write(Dictionary<string, string> customData, int coins) { customData["CoinPocket_CoinCount"] = Math.Max(0, coins).ToString(); } internal static int Local() { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { return Read(localPlayer.m_customData); } return 0; } internal static void SetLocal(int coins) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { Write(localPlayer.m_customData, coins); } } internal static bool TryDeposit(int balance, int amount, out int updated) { updated = balance; if (amount < 0 || balance > int.MaxValue - amount) { return false; } updated = balance + amount; return true; } internal static bool TryWithdraw(int balance, int amount, out int updated) { updated = balance; if (amount <= 0) { return true; } if (balance < amount) { return false; } updated = balance - amount; return true; } internal static int AfterPurchase(int balance, int price, int paidFromCarried) { int num = price - paidFromCarried; if (num <= 0) { return balance; } return balance - Math.Min(balance, num); } } internal static class CoinPlacement { internal static bool MoveInto(Inventory target, Inventory? source, ItemData item, int amount, int x, int y) { ItemData itemAt = target.GetItemAt(x, y); if (itemAt != null) { SharedData shared = itemAt.m_shared; if (shared != null && shared.m_name == "$item_coins") { return TopUp(target, source, item, amount, itemAt); } } int stack = item.m_stack; bool result = target.AddItem(item, amount, x, y, false); if (stack - item.m_stack > 0) { if (item.m_stack <= 0 && source != null) { source.RemoveItem(item); } if (source != null) { source.Changed(false, false); } target.Changed(false, false); } return result; } private static bool TopUp(Inventory target, Inventory? source, ItemData item, int amount, ItemData stack) { int num = Math.Min(amount, item.m_stack); int num2 = Math.Min(Math.Max(0, stack.m_shared.m_maxStackSize - stack.m_stack), num); if (num2 <= 0) { return false; } stack.m_stack += num2; item.m_stack -= num2; if (item.m_stack <= 0 && source != null) { source.RemoveItem(item); } target.Changed(false, false); if (source != null) { source.Changed(false, false); } return num2 == num; } } internal sealed class DepositHandlers { internal static readonly DepositHandlers Shared = new DepositHandlers(); private readonly List<DepositHandler> _handlers = new List<DepositHandler>(); private readonly HashSet<string> _warnedNames = new HashSet<string>(); internal void Register(string name, Func<Inventory, ItemData, int, bool> canDeposit, Func<Inventory, ItemData, int, bool> deposit, Func<Inventory, ItemData, int, string> describe) { DepositHandler depositHandler = new DepositHandler(name, canDeposit, deposit, describe, _warnedNames); int num = _handlers.FindIndex((DepositHandler existing) => existing.Name == name); if (num >= 0) { _handlers[num] = depositHandler; } else { _handlers.Add(depositHandler); } } internal void Unregister(string name) { _handlers.RemoveAll((DepositHandler handler) => handler.Name == name); } internal DepositHandler? Accepting(Inventory inventory, ItemData item, int amount) { DepositHandler[] array = _handlers.ToArray(); foreach (DepositHandler depositHandler in array) { if (depositHandler.CanDeposit(inventory, item, amount)) { return depositHandler; } } return null; } } internal sealed class DepositHandler { private readonly Func<Inventory, ItemData, int, bool> _canDeposit; private readonly Func<Inventory, ItemData, int, bool> _deposit; private readonly Func<Inventory, ItemData, int, string> _describe; private readonly HashSet<string> _warnedNames; internal string Name { get; } internal DepositHandler(string name, Func<Inventory, ItemData, int, bool> canDeposit, Func<Inventory, ItemData, int, bool> deposit, Func<Inventory, ItemData, int, string> describe, HashSet<string> warnedNames) { Name = name; _canDeposit = canDeposit; _deposit = deposit; _describe = describe; _warnedNames = warnedNames; } internal bool CanDeposit(Inventory inventory, ItemData item, int amount) { return Call(() => _canDeposit(inventory, item, amount), fallback: false); } internal bool Deposit(Inventory inventory, ItemData item, int amount) { return Call(() => _deposit(inventory, item, amount), fallback: false); } internal string Describe(Inventory inventory, ItemData item, int amount) { return Call(() => _describe(inventory, item, amount), "") ?? ""; } private T Call<T>(Func<T> callback, T fallback) { try { return callback(); } catch (Exception ex) { if (_warnedNames.Add(Name)) { Log.Warning("OttoPayApi: deposit handler '" + Name + "' threw: " + ex.Message); } return fallback; } } } internal static class Membership { internal static bool IsMember(Dictionary<string, string> customData) { if (customData.TryGetValue("OttoPay_BankMember", out string value) && value == "1") { return true; } return Balance.Read(customData) > 0; } internal static void Join(Dictionary<string, string> customData) { customData["OttoPay_BankMember"] = "1"; } internal static bool IsAuraPayOn(Dictionary<string, string> customData) { if (IsMember(customData) && customData.TryGetValue("OttoPay_AuraPay", out string value)) { return value == "1"; } return false; } internal static void SetAuraPay(Dictionary<string, string> customData, bool on) { customData["OttoPay_AuraPay"] = (on ? "1" : "0"); } internal static bool LocalIsMember() { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { return IsMember(localPlayer.m_customData); } return false; } } internal sealed class Withdrawal { internal static readonly Withdrawal Shared = new Withdrawal(); private Inventory? _coins; private bool _confirmed; internal void Open(Inventory coins) { _coins = coins; _confirmed = false; } internal bool Confirm(Dictionary<string, string> playerData, int amount) { Inventory? coins = _coins; ItemData val = ((coins != null) ? coins.GetAllItems().FirstOrDefault() : null); if (val == null) { return false; } Balance.Write(playerData, Balance.Read(playerData) - amount); val.m_stack = amount; _confirmed = true; return true; } internal int DragEnded(Dictionary<string, string> playerData) { if (_coins == null || !_confirmed) { return 0; } int num = 0; foreach (ItemData allItem in _coins.GetAllItems()) { num += allItem.m_stack; } _coins.RemoveAll(); _coins = null; _confirmed = false; Balance.Write(playerData, Balance.Read(playerData) + num); return num; } internal static bool MayLandOn(ItemData? occupant) { if (occupant != null) { return occupant.m_shared.m_name == "$item_coins"; } return true; } internal bool Owns(Inventory? inventory) { if (inventory != null) { return inventory == _coins; } return false; } internal static void Start() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown Player localPlayer = Player.m_localPlayer; int num = Balance.Local(); if (!((Object)(object)localPlayer == (Object)null) && num > 0) { if (Shared.DragEnded(localPlayer.m_customData) > 0) { num = Balance.Local(); } GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Coins"); Inventory val = new Inventory("CoinPocket_CoinCount", itemPrefab.GetComponent<ItemDrop>().m_itemData.GetIcon(), 1, 1); val.AddItem(itemPrefab, num); Shared.Open(val); InventoryGui.instance.ShowSplitDialog(val.GetAllItems().FirstOrDefault(), val); if (ZInput.GetKey((KeyCode)306, true) || ZInput.GetKey((KeyCode)305, true)) { SplitDialog splitDialog = InventoryGui.instance.m_splitDialog; splitDialog.SliderValue = splitDialog.m_splitSlider.maxValue; } } } internal static void ConfirmSplit(InventoryGui gui) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && Shared.Holds(gui.m_splitItem)) { gui.m_splitInventory = Shared._coins; if (Shared.Confirm(localPlayer.m_customData, (int)gui.m_splitDialog.SliderValue)) { BalancePanel.Refresh(); } } } private bool Holds(ItemData? item) { if (item != null && _coins != null) { return _coins.ContainsItem(item); } return false; } internal static bool IsWithdrawalDrag(Inventory? dragInventory) { if (dragInventory != null) { return dragInventory.m_name == "CoinPocket_CoinCount"; } return false; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry<T> SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } internal abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List<ZNetPeer> peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(0L, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable<bool> waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != 0) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List<IEnumerator<bool>> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfTy