Decompiled source of CasinoPersonalWallet v1.1.1

plugins/CasinoPersonalWallet/CasinoWallet.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCasino.Custom;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Saltanis.Economy;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyVersion("1.1.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 Saltanis.CasinoWallet
{
	internal static class CasinoPatches
	{
		[ThreadStatic]
		private static ulong? sender;

		internal static void Install(Harmony harmony)
		{
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Expected O, but got Unknown
			//IL_019f: Expected O, but got Unknown
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Expected O, but got Unknown
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Expected O, but got Unknown
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Expected O, but got Unknown
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Expected O, but got Unknown
			//IL_0290: Expected O, but got Unknown
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c4: Expected O, but got Unknown
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_030c: Expected O, but got Unknown
			//IL_030c: Expected O, but got Unknown
			Patch(harmony, CasinoWalletPlugin.Atm, "BuyChipsServerRpc", "BlockLegacyAtm");
			string[] array = new string[3] { "Buy10", "Buy50", "Buy100" };
			foreach (string name in array)
			{
				Patch(harmony, CasinoWalletPlugin.Atm, name, "Withdraw");
			}
			string[][] array2 = new string[6][]
			{
				new string[3] { "SlotMachine", "StartGambleServerRpc", "3409382145" },
				new string[3] { "Roulette", "PlaceBetServerRpc", "2110911173" },
				new string[3] { "TheWheel", "SpinWheelServerRpc", "2663771076" },
				new string[3] { "Blackjack", "JoinGameServerRpc", "3789166712" },
				new string[3] { "BeerTap", "BuyBeerServerRpc", "960726601" },
				new string[3] { "CigarBox", "BuyPipeServerRpc", "1214396420" }
			};
			foreach (string[] array3 in array2)
			{
				Type type = AccessTools.TypeByName("LethalCasino.Custom." + array3[0]);
				Patch(harmony, type, array3[1], "OnlyMoney");
				MethodInfo methodInfo = Required(type, "__rpc_handler_" + array3[2]);
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(CasinoPatches), "RpcEnter", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CasinoPatches), "RpcExit", (Type[])null), (HarmonyMethod)null);
			}
			harmony.Patch((MethodBase)Required(typeof(PlayerControllerB), "SetHoverTipAndCurrentInteractTrigger"), (HarmonyMethod)null, new HarmonyMethod(typeof(CasinoPatches), "Hover", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Required(typeof(GameNetworkManager), "SaveGame"), new HarmonyMethod(typeof(CasinoPatches), "Save", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Required(typeof(GrabbableObject), "SetScrapValue"), (HarmonyMethod)null, new HarmonyMethod(typeof(CasinoPatches), "ValueChanged", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Required(typeof(DepositItemsDesk), "SellItemsOnServer"), new HarmonyMethod(typeof(CasinoPatches), "BeforeSale", (Type[])null), new HarmonyMethod(typeof(CasinoPatches), "AfterSale", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Required(typeof(GameNetworkManager), "ResetSavedGameValues"), (HarmonyMethod)null, new HarmonyMethod(typeof(CasinoPatches), "Reset", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Required(typeof(GameNetworkManager), "SaveItemsInShip"), new HarmonyMethod(typeof(CasinoPatches), "BeforeSaveItems", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CasinoPatches), "AfterSaveItems", (Type[])null), (HarmonyMethod)null);
		}

		private static MethodInfo Required(Type type, string name)
		{
			return AccessTools.Method(type, name, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type?.FullName, name);
		}

		private static void Patch(Harmony harmony, Type type, string name, string prefix)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			harmony.Patch((MethodBase)Required(type, name), new HarmonyMethod(typeof(CasinoPatches), prefix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static bool BlockLegacyAtm()
		{
			return false;
		}

		private static bool Withdraw(Component __instance, PlayerControllerB __0, MethodBase __originalMethod)
		{
			CasinoWalletPlugin.Instance.Request(__instance, __0, int.Parse(__originalMethod.Name.Substring(3)));
			return false;
		}

		private static void RpcEnter(object[] __args, out ulong? __state)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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)
			__state = sender;
			object obj = __args[2];
			ServerRpcReceiveParams receive = ((ServerRpcParams)AccessTools.Field(obj.GetType(), "Server").GetValue(obj)).Receive;
			sender = receive.SenderClientId;
		}

		private static void RpcExit(ulong? __state)
		{
			sender = __state;
		}

		private static bool OnlyMoney(NetworkBehaviour __instance, object[] __args)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			NetworkBehaviourReference val = (NetworkBehaviourReference)__args[0];
			PlayerControllerB val2 = default(PlayerControllerB);
			if (!((NetworkBehaviourReference)(ref val)).TryGet<PlayerControllerB>(ref val2, (NetworkManager)null))
			{
				return false;
			}
			if (sender.HasValue && val2.actualClientId != sender.Value)
			{
				return false;
			}
			GrabbableObject val3 = CasinoWalletPlugin.Held(val2);
			if (!CasinoWalletPlugin.Money(val3))
			{
				Warn((Component)(object)__instance, val2);
				return false;
			}
			GrabbableObject val5 = default(GrabbableObject);
			if (__args.Length > 1 && __args[1] is NetworkBehaviourReference val4 && (!((NetworkBehaviourReference)(ref val4)).TryGet<GrabbableObject>(ref val5, (NetworkManager)null) || (Object)(object)val5 != (Object)(object)val3))
			{
				return false;
			}
			return true;
		}

		private static void Warn(Component machine, PlayerControllerB player)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)(object)CasinoWalletPlugin.Local)
			{
				CasinoWalletPlugin.Notice("The casino accepts money bags only. Withdraw a bag from your personal wallet at an ATM.");
			}
			else if (Object.op_Implicit((Object)(object)NetworkManager.Singleton) && NetworkManager.Singleton.IsServer)
			{
				AccessTools.Method(((object)machine).GetType(), "ShowWarningMessageClientRpc", (Type[])null, (Type[])null)?.Invoke(machine, new object[4]
				{
					NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)player),
					"Money bags only",
					"The casino accepts money bags only. Withdraw a bag from your personal wallet at an ATM.",
					true
				});
			}
		}

		private static void Hover(PlayerControllerB __instance)
		{
			InteractTrigger hoveringOverTrigger = __instance.hoveringOverTrigger;
			if (!Object.op_Implicit((Object)(object)hoveringOverTrigger) || !Object.op_Implicit((Object)(object)__instance.cursorTip))
			{
				return;
			}
			if (Object.op_Implicit((Object)(object)((Component)hoveringOverTrigger).GetComponentInParent<WalletAtm>()))
			{
				((TMP_Text)__instance.cursorTip).text = (hoveringOverTrigger.interactable ? hoveringOverTrigger.hoverTip : hoveringOverTrigger.disabledHoverTip);
				return;
			}
			Component component = ((Component)hoveringOverTrigger).GetComponent(CasinoWalletPlugin.Interactable);
			if (Object.op_Implicit((Object)(object)component) && CasinoWalletPlugin.Flag(component, "requireScrap") && !CasinoWalletPlugin.Flag(component, "gameInProgress") && !CasinoWalletPlugin.Money(CasinoWalletPlugin.Held(__instance)))
			{
				((TMP_Text)__instance.cursorTip).text = "Money bags only - withdraw a bag at an ATM";
			}
		}

		private static void Save()
		{
			CasinoWalletPlugin.Instance?.Save();
		}

		private static void Reset()
		{
			CasinoWalletPlugin.Instance?.ResetBook();
		}

		private static void ValueChanged(GrabbableObject __instance)
		{
			CasinoWalletPlugin.Instance?.RecordValue(__instance);
		}

		private static void BeforeSale(DepositItemsDesk __instance, out string[] __state)
		{
			__state = (((NetworkBehaviour)__instance).IsServer ? (from b in __instance.itemsOnCounter
				where Object.op_Implicit((Object)(object)b) && Object.op_Implicit((Object)(object)((Component)b).GetComponent<MoneyBag>())
				select ((Component)b).GetComponent<MoneyBag>().Id).ToArray() : null);
		}

		private static void AfterSale(string[] __state)
		{
			CasinoWalletPlugin.Instance?.Sold(__state);
		}

		private static void BeforeSaveItems(out Dictionary<GrabbableObject, bool> __state)
		{
			__state = (from t in Object.FindObjectsOfType<MoneyBag>()
				select ((Component)t).GetComponent<GrabbableObject>() into t
				where Object.op_Implicit((Object)(object)t)
				select t).ToDictionary((GrabbableObject t) => t, (GrabbableObject t) => t.deactivated);
			foreach (GrabbableObject key in __state.Keys)
			{
				key.deactivated = true;
			}
		}

		private static void AfterSaveItems(Dictionary<GrabbableObject, bool> __state)
		{
			if (__state == null)
			{
				return;
			}
			foreach (KeyValuePair<GrabbableObject, bool> item in __state)
			{
				if (Object.op_Implicit((Object)(object)item.Key))
				{
					item.Key.deactivated = item.Value;
				}
			}
		}
	}
	[BepInPlugin("saltanis.casinowallet", "Casino Personal Wallet", "1.1.1")]
	[BepInDependency("mrgrm7.LethalCasino", "1.1.3")]
	public sealed class CasinoWalletLoader : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		private void Awake()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Harmony val = new Harmony("saltanis.casinowallet");
			CasinoPatches.Install(val);
			val.Patch((MethodBase)AccessTools.Method(typeof(GameNetworkManager), "Start", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CasinoWalletLoader), "StartRuntime", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void StartRuntime()
		{
			CasinoWalletPlugin.EnsureRuntime();
		}
	}
	public sealed class CasinoWalletPlugin : MonoBehaviour
	{
		[Serializable]
		internal sealed class Bag
		{
			public string Id = "";

			public string Owner = "";

			public int Value;
		}

		[Serializable]
		internal sealed class Book
		{
			public List<Bag> Bags = new List<Bag>();
		}

		[Serializable]
		private sealed class BagState
		{
			public ulong Network;

			public string Id;

			public int Value;
		}

		[Serializable]
		private sealed class Snapshot
		{
			public long Balance;

			public bool WalletReady;

			public List<BagState> Bags = new List<BagState>();

			public string Notice = "";
		}

		public const string Id = "saltanis.casinowallet";

		public const string Version = "1.1.1";

		public const string SaveKey = "Saltanis.CasinoWallet.v1";

		private const string Command = "saltanis.casinowallet/1/command";

		private const string State = "saltanis.casinowallet/1/state";

		internal static CasinoWalletPlugin Instance;

		internal static readonly JsonSerializerSettings Json = new JsonSerializerSettings
		{
			TypeNameHandling = (TypeNameHandling)0,
			MetadataPropertyHandling = (MetadataPropertyHandling)2,
			MaxDepth = 12
		};

		private NetworkManager network;

		private string slot;

		private Book book;

		private float nextPoll;

		private float nextSync;

		private long localBalance;

		private long displayedBalance = -1L;

		private readonly Dictionary<string, GrabbableObject> live = new Dictionary<string, GrabbableObject>();

		private readonly HashSet<string> delivered = new HashSet<string>();

		private readonly Dictionary<ulong, float> lastCommand = new Dictionary<ulong, float>();

		private readonly WalletHud hud = new WalletHud((Func<long, string>)Amount, (Func<string>)(() => "+{0}"));

		private Snapshot snapshot;

		internal static readonly Type Atm = AccessTools.TypeByName("LethalCasino.Custom.AtmMachine");

		internal static readonly Type Scrap = AccessTools.TypeByName("LethalCasino.Custom.CustomScrapController");

		internal static readonly Type CasinoPlayer = AccessTools.TypeByName("LethalCasino.Custom.CustomPlayerController");

		internal static readonly Type Interactable = AccessTools.TypeByName("LethalCasino.Custom.InteractableCasinoComponent");

		private ManualLogSource Logger => CasinoWalletLoader.Log;

		internal static PlayerControllerB Local
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)GameNetworkManager.Instance))
				{
					return null;
				}
				return GameNetworkManager.Instance.localPlayerController;
			}
		}

		public static string Amount(long cents)
		{
			return ((decimal)cents / 100m).ToString("0.00", CultureInfo.GetCultureInfo("pl-PL")) + " BM";
		}

		internal static GrabbableObject Held(PlayerControllerB player)
		{
			if (!Object.op_Implicit((Object)(object)player) || player.ItemSlots == null || player.currentItemSlot < 0 || player.currentItemSlot >= player.ItemSlots.Length)
			{
				return null;
			}
			return player.ItemSlots[player.currentItemSlot];
		}

		internal static bool Flag(Component component, string field)
		{
			if (Object.op_Implicit((Object)(object)component))
			{
				return (bool)AccessTools.Field(((object)component).GetType(), field).GetValue(component);
			}
			return false;
		}

		internal static bool Locked(GrabbableObject bag)
		{
			if (Object.op_Implicit((Object)(object)bag))
			{
				return Flag(((Component)bag).GetComponent(Scrap), "lockFromGambling");
			}
			return false;
		}

		internal static bool Gambling(PlayerControllerB player)
		{
			if (Object.op_Implicit((Object)(object)player))
			{
				return Flag(((Component)player).GetComponent(CasinoPlayer), "isGambling");
			}
			return false;
		}

		internal static bool Money(GrabbableObject item)
		{
			if (Object.op_Implicit((Object)(object)item) && Object.op_Implicit((Object)(object)((Component)item).GetComponent<MoneyBag>()) && !string.IsNullOrEmpty(((Component)item).GetComponent<MoneyBag>().Id))
			{
				return item.scrapValue > 0;
			}
			return false;
		}

		private static void SetField(Component component, string name, object value)
		{
			if (Object.op_Implicit((Object)(object)component))
			{
				AccessTools.Field(((object)component).GetType(), name).SetValue(component, value);
			}
		}

		private void Awake()
		{
			Instance = this;
			CrewWallet.Attach(((Component)this).gameObject);
			Logger.LogInfo((object)"Casino Personal Wallet: 1 BM = 1 casino unit; scrap payments disabled.");
		}

		internal static void EnsureRuntime()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)Instance))
			{
				GameObject val = new GameObject("Casino Personal Wallet Runtime");
				Object.DontDestroyOnLoad((Object)val);
				val.AddComponent<CasinoWalletPlugin>();
			}
		}

		private void Update()
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			NetworkManager val = NetworkManager.Singleton;
			if (!Object.op_Implicit((Object)(object)val) || !val.IsListening || val.CustomMessagingManager == null)
			{
				val = null;
			}
			if (val != network)
			{
				Unbind();
				network = val;
				slot = null;
				book = null;
				live.Clear();
				delivered.Clear();
				lastCommand.Clear();
				snapshot = null;
				nextPoll = (nextSync = 0f);
				localBalance = 0L;
				displayedBalance = -1L;
				if (Object.op_Implicit((Object)(object)network))
				{
					network.CustomMessagingManager.RegisterNamedMessageHandler("saltanis.casinowallet/1/command", new HandleNamedMessageDelegate(ReceiveCommand));
					network.CustomMessagingManager.RegisterNamedMessageHandler("saltanis.casinowallet/1/state", new HandleNamedMessageDelegate(ReceiveState));
				}
			}
			if (!Object.op_Implicit((Object)(object)network))
			{
				hud.Clear();
				return;
			}
			if (Time.unscaledTime >= nextPoll)
			{
				nextPoll = Time.unscaledTime + 0.35f;
				foreach (Component item in Object.FindObjectsOfType(Atm).Cast<Component>())
				{
					ConfigureAtm(item);
				}
				if (network.IsServer && Ready())
				{
					RefreshBook();
					Component val2 = Object.FindObjectsOfType(Atm).Cast<Component>().FirstOrDefault();
					if (Object.op_Implicit((Object)(object)val2) && StartOfRound.Instance.shipHasLanded && !StartOfRound.Instance.shipIsLeaving)
					{
						Bag[] array = book.Bags.Where((Bag b) => b.Value > 0 && !delivered.Contains(b.Id)).ToArray();
						foreach (Bag bag in array)
						{
							if (Object.op_Implicit((Object)(object)FindPlayer(bag.Owner)))
							{
								Deliver(val2, bag);
							}
						}
					}
					if (Time.unscaledTime >= nextSync)
					{
						nextSync = Time.unscaledTime + 1f;
						foreach (ulong connectedClientsId in network.ConnectedClientsIds)
						{
							Publish(connectedClientsId);
						}
					}
				}
				else
				{
					ApplySnapshot();
				}
			}
			if (Chainloader.PluginInfos.ContainsKey("saltanis.companygym") || Chainloader.PluginInfos.ContainsKey("saltanis.zabkowysklep"))
			{
				return;
			}
			bool num2;
			if (!network.IsServer)
			{
				if (snapshot != null)
				{
					num2 = snapshot.WalletReady;
					goto IL_02d1;
				}
			}
			else if (Ready())
			{
				num2 = CrewWallet.Key(Local) != null;
				goto IL_02d1;
			}
			goto IL_02d3;
			IL_02d3:
			hud.Clear();
			displayedBalance = -1L;
			return;
			IL_02d1:
			if (num2)
			{
				long num3 = (network.IsServer ? CrewWallet.Balance(Local) : localBalance);
				if (displayedBalance >= 0 && num3 > displayedBalance)
				{
					hud.RecordPayout(num3 - displayedBalance);
				}
				displayedBalance = num3;
				hud.Update(Local, num3);
				return;
			}
			goto IL_02d3;
		}

		private bool Ready()
		{
			if (!Object.op_Implicit((Object)(object)network) || !network.IsServer || !CrewWallet.IsActive)
			{
				return false;
			}
			string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName;
			if (slot == currentSaveFileName)
			{
				return this.book != null;
			}
			slot = currentSaveFileName;
			this.book = null;
			live.Clear();
			delivered.Clear();
			try
			{
				Book book = JsonConvert.DeserializeObject<Book>(ES3.Load<string>("Saltanis.CasinoWallet.v1", slot, "{\"Bags\":[]}"), Json);
				if (book?.Bags == null || book.Bags.Count > 4096 || book.Bags.Any((Bag b) => b == null || !Guid.TryParseExact(b.Id, "N", out var _) || string.IsNullOrEmpty(b.Owner) || b.Owner.Length > 150 || b.Value < 0) || (from b in book.Bags
					group b by b.Id).Any((IGrouping<string, Bag> g) => g.Count() > 1))
				{
					throw new FormatException("Invalid casino wallet save.");
				}
				this.book = book;
			}
			catch (Exception ex)
			{
				Logger.LogError((object)ex);
			}
			return this.book != null;
		}

		private static PlayerControllerB FindPlayer(ulong client)
		{
			if (!Object.op_Implicit((Object)(object)StartOfRound.Instance))
			{
				return null;
			}
			return ((IEnumerable<PlayerControllerB>)StartOfRound.Instance.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB p) => Object.op_Implicit((Object)(object)p) && p.isPlayerControlled && p.actualClientId == client));
		}

		private static PlayerControllerB FindPlayer(string key)
		{
			if (!Object.op_Implicit((Object)(object)StartOfRound.Instance))
			{
				return null;
			}
			return ((IEnumerable<PlayerControllerB>)StartOfRound.Instance.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB p) => Object.op_Implicit((Object)(object)p) && p.isPlayerControlled && CrewWallet.Key(p) == key));
		}

		internal unsafe void Request(Component atm, PlayerControllerB player, int amount)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)network) || (Object)(object)player != (Object)(object)Local || !Object.op_Implicit((Object)(object)atm) || !Object.op_Implicit((Object)(object)atm.GetComponent<NetworkObject>()) || !atm.GetComponent<NetworkObject>().IsSpawned)
			{
				return;
			}
			ulong networkObjectId = atm.GetComponent<NetworkObject>().NetworkObjectId;
			if (network.IsServer)
			{
				Execute(network.LocalClientId, networkObjectId, amount);
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(16, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref networkObjectId, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref amount, default(ForPrimitives));
				network.CustomMessagingManager.SendNamedMessage("saltanis.casinowallet/1/command", 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private void ReceiveCommand(ulong sender, FastBufferReader reader)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)network) && network.IsServer && ((FastBufferReader)(ref reader)).Length - ((FastBufferReader)(ref reader)).Position == 12)
			{
				ulong atmId = default(ulong);
				((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref atmId, default(ForPrimitives));
				int amount = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref amount, default(ForPrimitives));
				Execute(sender, atmId, amount);
			}
		}

		private void Execute(ulong sender, ulong atmId, int amount)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			if (!Ready() || !network.ConnectedClients.ContainsKey(sender) || !network.SpawnManager.SpawnedObjects.TryGetValue(atmId, out var value) || !Object.op_Implicit((Object)(object)((Component)value).GetComponent(Atm)))
			{
				return;
			}
			PlayerControllerB val = FindPlayer(sender);
			StartOfRound instance = StartOfRound.Instance;
			if (!Object.op_Implicit((Object)(object)val) || val.isPlayerDead || !instance.shipHasLanded || instance.shipIsLeaving || instance.currentLevel.sceneName != "CompanyBuilding")
			{
				return;
			}
			WalletAtm component = ((Component)value).GetComponent<WalletAtm>();
			Vector3 val2 = ((amount == 0 && Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.DepositRoot)) ? component.DepositRoot.transform.position : ((Component)value).transform.position);
			if ((amount == 0 && (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)component.DepositRoot))) || Vector3.Distance(((Component)val).transform.position, val2) > ((amount == 0) ? 4f : 6f) || (lastCommand.TryGetValue(sender, out var value2) && Time.unscaledTime < value2 + 0.5f))
			{
				return;
			}
			lastCommand[sender] = Time.unscaledTime;
			if (Gambling(val) || Locked(Held(val)))
			{
				Publish(sender, "Finish your wager before using a wallet machine.");
				return;
			}
			try
			{
				switch (amount)
				{
				case 0:
					CashIn(sender, val);
					break;
				case 10:
				case 50:
				case 100:
					Withdraw(sender, val, ((Component)value).GetComponent(Atm), amount);
					break;
				}
			}
			catch (Exception ex)
			{
				Logger.LogError((object)ex);
				Publish(sender, "Unable to save this exchange. Try again.");
			}
		}

		private void Withdraw(ulong sender, PlayerControllerB player, Component atm, int amount)
		{
			RefreshBook();
			if (this.book.Bags.Count >= 4096)
			{
				Publish(sender, "Deposit some bags before making another withdrawal.");
				return;
			}
			string text = CrewWallet.Key(player);
			if (text == null)
			{
				Publish(sender, "Your personal wallet is synchronizing.");
				return;
			}
			Book book = CopyBook();
			Bag bag = new Bag
			{
				Id = Guid.NewGuid().ToString("N"),
				Owner = text,
				Value = amount
			};
			book.Bags.Add(bag);
			if (!CrewWallet.TryPurchase(player, (long)amount * 100L, "Saltanis.CasinoWallet.v1", JsonConvert.SerializeObject((object)book, Json)))
			{
				Publish(sender, "Insufficient personal funds. Cost: " + Amount((long)amount * 100L) + ".");
				return;
			}
			this.book = book;
			Deliver(atm, bag);
			Publish(sender, "Money bag withdrawn: " + amount + ". Cost: " + Amount((long)amount * 100L) + ".");
		}

		private void CashIn(ulong sender, PlayerControllerB player)
		{
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			GrabbableObject val = Held(player);
			if (!Money(val))
			{
				Publish(sender, "Hold a money bag withdrawn from a casino ATM.");
				return;
			}
			MoneyBag tag = ((Component)val).GetComponent<MoneyBag>();
			if (!live.TryGetValue(tag.Id, out var value) || (Object)(object)value != (Object)(object)val || Locked(val))
			{
				return;
			}
			RefreshBook();
			Book book = CopyBook();
			Bag bag = book.Bags.Find((Bag b) => b.Id == tag.Id);
			if (bag == null || bag.Value <= 0)
			{
				return;
			}
			int value2 = bag.Value;
			book.Bags.Remove(bag);
			if (!CrewWallet.TryGrantBatch("casino:" + bag.Id, new string[1] { CrewWallet.Key(player) }, (long)value2 * 100L, "Saltanis.CasinoWallet.v1", JsonConvert.SerializeObject((object)book, Json)))
			{
				Publish(sender, "Deposit failed. Your money bag has been kept.");
				return;
			}
			this.book = book;
			live.Remove(bag.Id);
			delivered.Add(bag.Id);
			tag.Id = "";
			val.scrapValue = 0;
			CasinoManager val2 = Object.FindObjectsOfType<CasinoManager>().FirstOrDefault();
			if (Object.op_Implicit((Object)(object)val2))
			{
				val2.DespawnCasinoItemServerRpc(NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)val), false);
			}
			Publish(sender, "Deposited into your personal wallet: " + Amount((long)value2 * 100L) + ".");
		}

		private Book CopyBook()
		{
			return new Book
			{
				Bags = book.Bags.Select((Bag b) => new Bag
				{
					Id = b.Id,
					Owner = b.Owner,
					Value = b.Value
				}).ToList()
			};
		}

		private void Deliver(Component atm, Bag entry)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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)
			GameObject val = null;
			try
			{
				Vector3 val2 = (Vector3)AccessTools.Field(Atm, "spawnOffset").GetValue(atm);
				val = CasinoManager.Spawn("ChipBag", val2 + new Vector3(Random.Range(-0.6f, 0.6f), 0f, Random.Range(-0.3f, 0.3f)), Quaternion.Euler(0f, 90f, 0f));
				GrabbableObject component = val.GetComponent<GrabbableObject>();
				if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)((NetworkBehaviour)component).NetworkObject) || !((NetworkBehaviour)component).NetworkObject.IsSpawned)
				{
					throw new InvalidOperationException("Casino bag did not spawn.");
				}
				Mark(component, entry.Id, entry.Value);
				CasinoManager.ChipBags.Add(val);
				live.Add(entry.Id, component);
				delivered.Add(entry.Id);
				foreach (ulong connectedClientsId in network.ConnectedClientsIds)
				{
					Publish(connectedClientsId);
				}
			}
			catch (Exception ex)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					NetworkObject component2 = val.GetComponent<NetworkObject>();
					if (Object.op_Implicit((Object)(object)component2) && component2.IsSpawned)
					{
						component2.Despawn(true);
					}
					else
					{
						Object.Destroy((Object)(object)val);
					}
				}
				Logger.LogError((object)("Bag delivery retained for retry: " + ex));
			}
		}

		private static void Mark(GrabbableObject item, string id, int value)
		{
			MoneyBag moneyBag = ((Component)item).GetComponent<MoneyBag>() ?? ((Component)item).gameObject.AddComponent<MoneyBag>();
			moneyBag.Id = id;
			if ((Object)(object)moneyBag.Properties == (Object)null)
			{
				moneyBag.Properties = Object.Instantiate<Item>(item.itemProperties);
				moneyBag.Properties.itemName = "Money bag";
				moneyBag.Properties.isScrap = true;
				item.itemProperties = moneyBag.Properties;
			}
			SetField(((Component)item).GetComponent(Scrap) ?? ((Component)item).gameObject.AddComponent(Scrap), "destroyOnZeroValue", true);
			if (item.scrapValue != value)
			{
				item.SetScrapValue(value);
			}
		}

		private void RefreshBook()
		{
			if (book == null)
			{
				return;
			}
			foreach (Bag bag in book.Bags)
			{
				if (!live.TryGetValue(bag.Id, out var value))
				{
					continue;
				}
				if (!Object.op_Implicit((Object)(object)value))
				{
					bag.Value = 0;
					continue;
				}
				bag.Value = Math.Max(0, value.scrapValue);
				if (Object.op_Implicit((Object)(object)value.playerHeldBy) && CrewWallet.Key(value.playerHeldBy) != null)
				{
					bag.Owner = CrewWallet.Key(value.playerHeldBy);
				}
			}
			book.Bags.RemoveAll((Bag b) => b.Value <= 0 && (!live.TryGetValue(b.Id, out var value2) || !Object.op_Implicit((Object)(object)value2) || !Locked(value2)));
		}

		internal void Save()
		{
			if (Ready())
			{
				RefreshBook();
				ES3.Save<string>("Saltanis.CasinoWallet.v1", JsonConvert.SerializeObject((object)book, Json), slot);
			}
		}

		internal void RecordValue(GrabbableObject item)
		{
			if (!Object.op_Implicit((Object)(object)network) || !network.IsServer || book == null || !Object.op_Implicit((Object)(object)item))
			{
				return;
			}
			MoneyBag tag = ((Component)item).GetComponent<MoneyBag>();
			if (Object.op_Implicit((Object)(object)tag) && live.ContainsKey(tag.Id))
			{
				Bag bag = book.Bags.Find((Bag b) => b.Id == tag.Id);
				if (bag != null)
				{
					bag.Value = Math.Max(0, item.scrapValue);
				}
				Save();
			}
		}

		internal void Sold(string[] ids)
		{
			if (Object.op_Implicit((Object)(object)network) && network.IsServer && book != null && ids != null && ids.Length != 0)
			{
				book.Bags.RemoveAll((Bag b) => ids.Contains(b.Id));
				string[] array = ids;
				foreach (string key in array)
				{
					live.Remove(key);
				}
				Save();
			}
		}

		private unsafe void Publish(ulong client, string notice = "")
		{
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)network) || !network.IsServer || book == null)
			{
				return;
			}
			PlayerControllerB val = FindPlayer(client);
			bool flag = CrewWallet.IsActive && Object.op_Implicit((Object)(object)val) && CrewWallet.Key(val) != null;
			Snapshot snapshot = new Snapshot
			{
				Balance = (flag ? CrewWallet.Balance(val) : 0),
				WalletReady = flag,
				Notice = notice
			};
			foreach (KeyValuePair<string, GrabbableObject> item in live)
			{
				if (Object.op_Implicit((Object)(object)item.Value) && Object.op_Implicit((Object)(object)((NetworkBehaviour)item.Value).NetworkObject) && ((NetworkBehaviour)item.Value).NetworkObject.IsSpawned && Money(item.Value))
				{
					snapshot.Bags.Add(new BagState
					{
						Network = ((NetworkBehaviour)item.Value).NetworkObjectId,
						Id = item.Key,
						Value = item.Value.scrapValue
					});
				}
			}
			if (client == network.LocalClientId)
			{
				localBalance = snapshot.Balance;
				if (notice.Length > 0)
				{
					Notice(notice);
				}
				return;
			}
			string text = JsonConvert.SerializeObject((object)snapshot, Json);
			FastBufferWriter val2 = default(FastBufferWriter);
			((FastBufferWriter)(ref val2))..ctor(1024, (Allocator)2, 1048576);
			try
			{
				((FastBufferWriter)(ref val2)).WriteValueSafe(text, false);
				network.CustomMessagingManager.SendNamedMessage("saltanis.casinowallet/1/state", client, val2, (NetworkDelivery)4);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val2))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private void ReceiveState(ulong sender, FastBufferReader reader)
		{
			if (!Object.op_Implicit((Object)(object)network) || network.IsServer || sender != 0L || ((FastBufferReader)(ref reader)).Length > 1048576)
			{
				return;
			}
			try
			{
				string text = default(string);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
				Snapshot snapshot = JsonConvert.DeserializeObject<Snapshot>(text, Json);
				if (snapshot?.Bags != null && snapshot.Balance >= 0 && snapshot.Bags.Count <= 4096 && !snapshot.Bags.Any((BagState b) => b == null || b.Value <= 0 || !Guid.TryParseExact(b.Id, "N", out var _)))
				{
					this.snapshot = snapshot;
					localBalance = snapshot.Balance;
					ApplySnapshot();
					if (!string.IsNullOrEmpty(snapshot.Notice))
					{
						Notice(snapshot.Notice);
					}
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning((object)("Invalid wallet state: " + ex.Message));
			}
		}

		private void ApplySnapshot()
		{
			if (snapshot == null || !Object.op_Implicit((Object)(object)network) || network.IsServer)
			{
				return;
			}
			BagState[] array = snapshot.Bags.ToArray();
			foreach (BagState bagState in array)
			{
				if (network.SpawnManager.SpawnedObjects.TryGetValue(bagState.Network, out var value))
				{
					GrabbableObject component = ((Component)value).GetComponent<GrabbableObject>();
					if (Object.op_Implicit((Object)(object)component))
					{
						Mark(component, bagState.Id, bagState.Value);
						snapshot.Bags.Remove(bagState);
					}
				}
			}
		}

		internal static void Notice(string message)
		{
			if (Object.op_Implicit((Object)(object)HUDManager.Instance))
			{
				HUDManager.Instance.DisplayTip("Casino Wallet", message, false, false, "LC_Tip1");
			}
		}

		internal void ConfigureAtm(Component atm)
		{
			if (!Object.op_Implicit((Object)(object)atm) || !Object.op_Implicit((Object)(object)atm.GetComponent<NetworkObject>()) || !atm.GetComponent<NetworkObject>().IsSpawned || Object.op_Implicit((Object)(object)atm.GetComponent<WalletAtm>()))
			{
				return;
			}
			atm.gameObject.AddComponent<WalletAtm>().Initialize(atm);
			foreach (Component item in atm.GetComponentsInChildren(Interactable, true).Cast<Component>())
			{
				SetField(item, "requireScrap", false);
				SetField(item, "hoverTipCurrentScrapValue", false);
			}
			int[] array = new int[3] { 10, 50, 100 };
			for (int i = 0; i < array.Length; i++)
			{
				int num = array[i];
				InteractTrigger component = ((Component)atm.transform.Find("Buy" + num)).GetComponent<InteractTrigger>();
				component.hoverTip = "Withdraw " + num + " for " + num + " BM : [E]";
				component.disabledHoverTip = component.hoverTip;
				component.interactable = true;
			}
		}

		private void Unbind()
		{
			if (Object.op_Implicit((Object)(object)network) && network.CustomMessagingManager != null)
			{
				network.CustomMessagingManager.UnregisterNamedMessageHandler("saltanis.casinowallet/1/command");
				network.CustomMessagingManager.UnregisterNamedMessageHandler("saltanis.casinowallet/1/state");
			}
		}

		private void OnDestroy()
		{
			Unbind();
			hud.Dispose();
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		internal void ResetBook()
		{
			if (!Object.op_Implicit((Object)(object)network) || !network.IsServer)
			{
				return;
			}
			GrabbableObject[] array = live.Values.ToArray();
			foreach (GrabbableObject val in array)
			{
				if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)((NetworkBehaviour)val).NetworkObject) && ((NetworkBehaviour)val).NetworkObject.IsSpawned)
				{
					((NetworkBehaviour)val).NetworkObject.Despawn(true);
				}
			}
			book = new Book();
			live.Clear();
			delivered.Clear();
			GameNetworkManager instance = GameNetworkManager.Instance;
			if (Object.op_Implicit((Object)(object)instance) && !string.IsNullOrEmpty(instance.currentSaveFileName))
			{
				ES3.Save<string>("Saltanis.CasinoWallet.v1", JsonConvert.SerializeObject((object)book, Json), instance.currentSaveFileName);
			}
		}
	}
	public sealed class MoneyBag : MonoBehaviour
	{
		internal string Id;

		internal Item Properties;

		private void OnDestroy()
		{
			if (Object.op_Implicit((Object)(object)Properties))
			{
				Object.Destroy((Object)(object)Properties);
			}
		}
	}
	public sealed class WalletAtm : MonoBehaviour
	{
		private Component atm;

		private TextMeshPro display;

		private readonly List<Material> materials = new List<Material>();

		private int shownValue = int.MinValue;

		private bool shownReady;

		public GameObject DepositRoot { get; private set; }

		public InteractTrigger DepositTrigger { get; private set; }

		internal void Initialize(Component owner)
		{
			atm = owner;
			Build();
			Update();
		}

		private Material Ink(string name, Color color, bool lit = false)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			Shader val = (lit ? Shader.Find("HDRP/Lit") : Shader.Find("HDRP/Unlit"));
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = Shader.Find("Unlit/Color") ?? Shader.Find("Standard");
			}
			Material val2 = new Material(val)
			{
				name = name,
				color = color
			};
			if (val2.HasProperty("_BaseColor"))
			{
				val2.SetColor("_BaseColor", color);
			}
			if (val2.HasProperty("_UnlitColor"))
			{
				val2.SetColor("_UnlitColor", color);
			}
			materials.Add(val2);
			return val2;
		}

		private void Box(string name, Vector3 position, Vector3 size, Material material, float angle = 0f)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3);
			((Object)obj).name = name;
			obj.transform.SetParent(DepositRoot.transform, false);
			obj.transform.localPosition = position;
			obj.transform.localScale = size;
			obj.transform.localRotation = Quaternion.Euler(0f, 0f, angle);
			Object.Destroy((Object)(object)obj.GetComponent<Collider>());
			((Renderer)obj.GetComponent<MeshRenderer>()).sharedMaterial = material;
		}

		private TextMeshPro Label(string name, string text, Vector3 position, float size, Color color, Vector2 area)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			TextMeshPro component = new GameObject(name, new Type[1] { typeof(TextMeshPro) }).GetComponent<TextMeshPro>();
			component.transform.SetParent(DepositRoot.transform, false);
			component.transform.localPosition = position;
			component.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
			((TMP_Text)component).text = text;
			((TMP_Text)component).fontSize = size;
			((TMP_Text)component).alignment = (TextAlignmentOptions)514;
			((Graphic)component).color = color;
			((TMP_Text)component).rectTransform.sizeDelta = area;
			((TMP_Text)component).enableWordWrapping = false;
			return component;
		}

		private void Build()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00e5: 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)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: 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_0131: 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_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: 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_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: 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_0352: Unknown result type (might be due to invalid IL or missing references)
			//IL_037d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0387: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0402: Unknown result type (might be due to invalid IL or missing references)
			//IL_0428: Unknown result type (might be due to invalid IL or missing references)
			//IL_043c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Unknown result type (might be due to invalid IL or missing references)
			//IL_0472: Unknown result type (might be due to invalid IL or missing references)
			//IL_047e: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0516: Unknown result type (might be due to invalid IL or missing references)
			//IL_052a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0550: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Unknown result type (might be due to invalid IL or missing references)
			//IL_058a: Unknown result type (might be due to invalid IL or missing references)
			//IL_059e: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0603: Unknown result type (might be due to invalid IL or missing references)
			//IL_060d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0619: Unknown result type (might be due to invalid IL or missing references)
			//IL_0639: Unknown result type (might be due to invalid IL or missing references)
			//IL_064d: Unknown result type (might be due to invalid IL or missing references)
			//IL_068e: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0701: Unknown result type (might be due to invalid IL or missing references)
			//IL_0706: Unknown result type (might be due to invalid IL or missing references)
			//IL_0711: Unknown result type (might be due to invalid IL or missing references)
			//IL_0723: Expected O, but got Unknown
			//IL_0751: Unknown result type (might be due to invalid IL or missing references)
			//IL_0778: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0803: Expected O, but got Unknown
			//IL_0809: Unknown result type (might be due to invalid IL or missing references)
			//IL_0813: Expected O, but got Unknown
			//IL_0819: Unknown result type (might be due to invalid IL or missing references)
			//IL_0823: Expected O, but got Unknown
			//IL_0829: Unknown result type (might be due to invalid IL or missing references)
			//IL_0833: Expected O, but got Unknown
			//IL_0839: Unknown result type (might be due to invalid IL or missing references)
			//IL_0843: Expected O, but got Unknown
			//IL_0849: Unknown result type (might be due to invalid IL or missing references)
			//IL_0853: Expected O, but got Unknown
			float num = 0.5f;
			Vector3 right = atm.transform.right;
			Renderer[] componentsInChildren = atm.GetComponentsInChildren<Renderer>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Bounds bounds = componentsInChildren[i].bounds;
				float num2 = Vector3.Dot(((Bounds)(ref bounds)).extents, new Vector3(Mathf.Abs(right.x), Mathf.Abs(right.y), Mathf.Abs(right.z)));
				num = Mathf.Max(num, Vector3.Dot(((Bounds)(ref bounds)).center - atm.transform.position, right) + num2);
			}
			DepositRoot = new GameObject("Wallet Deposit Machine");
			DepositRoot.transform.SetParent(atm.transform, false);
			DepositRoot.transform.position = atm.transform.position + right * (num + 0.68f);
			DepositRoot.transform.rotation = atm.transform.rotation;
			Vector3 lossyScale = atm.transform.lossyScale;
			DepositRoot.transform.localScale = new Vector3(1.15f / lossyScale.x, 1.15f / lossyScale.y, 1.15f / lossyScale.z);
			Material material = Ink("Deposit dark steel", new Color(0.11f, 0.15f, 0.16f), lit: true);
			Material material2 = Ink("Deposit brushed trim", new Color(0.34f, 0.39f, 0.38f), lit: true);
			Material material3 = Ink("Deposit inset", new Color(0.012f, 0.024f, 0.026f));
			Material material4 = Ink("Deposit green indicator", new Color(0.25f, 0.86f, 0.49f));
			Color color = default(Color);
			((Color)(ref color))..ctor(0.88f, 1f, 0.91f);
			Box("Foot", new Vector3(0f, 0.065f, 0f), new Vector3(0.94f, 0.13f, 0.72f), material2);
			Box("Cabinet", new Vector3(0f, 0.95f, 0f), new Vector3(0.86f, 1.68f, 0.64f), material);
			Box("Left rail", new Vector3(-0.405f, 1.05f, 0.345f), new Vector3(0.045f, 1.42f, 0.045f), material2);
			Box("Right rail", new Vector3(0.405f, 1.05f, 0.345f), new Vector3(0.045f, 1.42f, 0.045f), material2);
			Box("Header border", new Vector3(0f, 1.69f, 0.34f), new Vector3(0.81f, 0.26f, 0.07f), material4);
			Box("Header inset", new Vector3(0f, 1.69f, 0.382f), new Vector3(0.77f, 0.22f, 0.025f), material3);
			Label("Deposit title", "DEPOSIT", new Vector3(0f, 1.72f, 0.401f), 0.9f, color, new Vector2(0.75f, 0.15f));
			Label("Wallet subtitle", "PERSONAL WALLET", new Vector3(0f, 1.62f, 0.402f), 0.45f, color, new Vector2(0.75f, 0.07f));
			Box("Screen frame", new Vector3(0f, 1.37f, 0.35f), new Vector3(0.7f, 0.32f, 0.075f), material2);
			Box("Screen", new Vector3(0f, 1.37f, 0.396f), new Vector3(0.65f, 0.27f, 0.025f), material3);
			display = Label("Deposit status", "HOLD A\nMONEY BAG", new Vector3(0f, 1.37f, 0.417f), 0.65f, color, new Vector2(0.63f, 0.25f));
			Box("Intake guard", new Vector3(0f, 1.04f, 0.37f), new Vector3(0.65f, 0.18f, 0.13f), material2);
			Box("Bag intake", new Vector3(0f, 1.045f, 0.444f), new Vector3(0.55f, 0.095f, 0.035f), material3);
			Box("Intake light", new Vector3(0f, 1.13f, 0.449f), new Vector3(0.55f, 0.018f, 0.02f), material4);
			Box("Arrow stem", new Vector3(0f, 0.79f, 0.339f), new Vector3(0.035f, 0.16f, 0.025f), material4);
			Box("Arrow left", new Vector3(-0.044f, 0.73f, 0.34f), new Vector3(0.035f, 0.13f, 0.025f), material4, 45f);
			Box("Arrow right", new Vector3(0.044f, 0.73f, 0.34f), new Vector3(0.035f, 0.13f, 0.025f), material4, -45f);
			Label("Deposit action", "INSERT MONEY BAG", new Vector3(0f, 0.59f, 0.342f), 0.5f, color, new Vector2(0.73f, 0.09f));
			Box("Service panel", new Vector3(0f, 0.34f, 0.332f), new Vector3(0.66f, 0.28f, 0.035f), material3);
			for (int j = 0; j < 4; j++)
			{
				Box("Vent " + j, new Vector3(0f, 0.26f + (float)j * 0.05f, 0.358f), new Vector3(0.49f, 0.018f, 0.02f), material2);
			}
			BoxCollider obj = DepositRoot.AddComponent<BoxCollider>();
			obj.center = new Vector3(0f, 0.94f, 0f);
			obj.size = new Vector3(0.86f, 1.76f, 0.64f);
			GameObject val = new GameObject("Deposit money bag")
			{
				tag = "InteractTrigger",
				layer = LayerMask.NameToLayer("InteractableObject")
			};
			val.transform.SetParent(DepositRoot.transform, false);
			val.transform.localPosition = new Vector3(0f, 1.045f, 0.49f);
			BoxCollider obj2 = val.AddComponent<BoxCollider>();
			((Collider)obj2).isTrigger = true;
			obj2.size = new Vector3(0.63f, 0.23f, 0.12f);
			DepositTrigger = val.AddComponent<InteractTrigger>();
			DepositTrigger.oneHandedItemAllowed = (DepositTrigger.twoHandedItemAllowed = true);
			DepositTrigger.holdInteraction = true;
			DepositTrigger.timeToHold = 0.65f;
			DepositTrigger.interactCooldown = false;
			DepositTrigger.hoverTip = "Deposit money bag : [E]";
			DepositTrigger.holdTip = "Depositing...";
			DepositTrigger.onInteract = new InteractEvent();
			DepositTrigger.onInteractEarly = new InteractEvent();
			DepositTrigger.onInteractEarlyOtherClients = new InteractEvent();
			DepositTrigger.onStopInteract = new InteractEvent();
			DepositTrigger.onCancelAnimation = new InteractEvent();
			DepositTrigger.holdingInteractEvent = new InteractEventFloat();
			((UnityEvent<PlayerControllerB>)(object)DepositTrigger.onInteract).AddListener((UnityAction<PlayerControllerB>)delegate(PlayerControllerB player)
			{
				CasinoWalletPlugin.Instance?.Request(atm, player, 0);
			});
			shownValue = int.MinValue;
		}

		private void Update()
		{
			if (Object.op_Implicit((Object)(object)atm) && Object.op_Implicit((Object)(object)DepositRoot))
			{
				PlayerControllerB local = CasinoWalletPlugin.Local;
				GrabbableObject val = CasinoWalletPlugin.Held(local);
				StartOfRound instance = StartOfRound.Instance;
				bool flag = Object.op_Implicit((Object)(object)instance) && instance.shipHasLanded && !instance.shipIsLeaving && !instance.inShipPhase;
				bool flag2 = flag && CasinoWalletPlugin.Money(val) && !CasinoWalletPlugin.Locked(val) && !CasinoWalletPlugin.Gambling(local);
				int num = (CasinoWalletPlugin.Money(val) ? val.scrapValue : 0);
				DepositTrigger.interactable = flag2;
				DepositTrigger.disabledHoverTip = ((!flag) ? "Available after landing" : ((num == 0) ? "Hold a money bag" : "Finish your wager before depositing"));
				if (num != shownValue || flag2 != shownReady)
				{
					shownValue = num;
					shownReady = flag2;
					((TMP_Text)display).text = ((num > 0) ? ((flag2 ? "DEPOSIT " : "BAG IN USE\n") + num + " BM") : "HOLD A\nMONEY BAG");
				}
			}
		}

		private void OnDestroy()
		{
			if (Object.op_Implicit((Object)(object)DepositRoot))
			{
				Object.Destroy((Object)(object)DepositRoot);
			}
			foreach (Material material in materials)
			{
				if (Object.op_Implicit((Object)(object)material))
				{
					Object.Destroy((Object)(object)material);
				}
			}
			materials.Clear();
		}
	}
}

plugins/CasinoPersonalWallet/SaltanisWallet.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 Saltanis.Economy
{
	[HarmonyPatch]
	public sealed class CrewWallet : MonoBehaviour
	{
		[Serializable]
		private sealed class Account
		{
			public string Player = "";

			public long Balance;

			public int LastParticipation = -1;
		}

		[Serializable]
		private sealed class Ledger
		{
			public List<Account> Wallets = new List<Account>();

			public List<string> RewardReceipts = new List<string>();
		}

		public const string SaveKey = "Saltanis.PersonalWallet.v1";

		private static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings
		{
			TypeNameHandling = (TypeNameHandling)0,
			MetadataPropertyHandling = (MetadataPropertyHandling)2,
			MaxDepth = 16
		};

		private const string LegacyKey = "saltanis.zabkowysklep.campaign.v1";

		private const string IdentityMessage = "Saltanis.Wallet/1/identity";

		private static CrewWallet instance;

		public static Func<DepositItemsDesk, int> SupplementalSaleValue;

		private NetworkManager network;

		private string slot;

		private string localId;

		private Ledger ledger;

		private readonly Dictionary<ulong, string> identities = new Dictionary<ulong, string>();

		private float nextPoll;

		private float nextIdentity;

		public static bool IsActive
		{
			get
			{
				if (Object.op_Implicit((Object)(object)instance))
				{
					return instance.Ready();
				}
				return false;
			}
		}

		public static event Action<string, long> Paid;

		public static void Attach(GameObject owner)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)instance))
			{
				instance = owner.GetComponent<CrewWallet>() ?? owner.AddComponent<CrewWallet>();
				new Harmony("saltanis.personalwallet.v1").PatchAll(typeof(CrewWallet));
			}
		}

		private unsafe void Update()
		{
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Expected O, but got Unknown
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager val = NetworkManager.Singleton;
			if (!Object.op_Implicit((Object)(object)val) || !val.IsListening || val.CustomMessagingManager == null)
			{
				val = null;
			}
			if (val != network)
			{
				if (Object.op_Implicit((Object)(object)network) && network.CustomMessagingManager != null)
				{
					network.CustomMessagingManager.UnregisterNamedMessageHandler("Saltanis.Wallet/1/identity");
					network.OnClientDisconnectCallback -= Forget;
				}
				network = val;
				slot = null;
				ledger = null;
				identities.Clear();
				nextIdentity = 0f;
				nextPoll = 0f;
				if (Object.op_Implicit((Object)(object)network) && val.CustomMessagingManager != null)
				{
					if (val.IsServer)
					{
						val.CustomMessagingManager.RegisterNamedMessageHandler("Saltanis.Wallet/1/identity", new HandleNamedMessageDelegate(Identity));
					}
					val.OnClientDisconnectCallback += Forget;
				}
			}
			if (!Object.op_Implicit((Object)(object)network) || Time.unscaledTime < nextPoll)
			{
				return;
			}
			nextPoll = Time.unscaledTime + 0.35f;
			GameNetworkManager val2 = GameNetworkManager.Instance;
			if (Object.op_Implicit((Object)(object)val2) && val2.disableSteam && Object.op_Implicit((Object)(object)val2.localPlayerController))
			{
				if (localId == null)
				{
					localId = ES3.Load<string>("CompanyGym.LocalIdentity", "LCGeneralSaveData", "");
					if (!Guid.TryParseExact(localId, "N", out var _))
					{
						localId = Guid.NewGuid().ToString("N");
						ES3.Save<string>("CompanyGym.LocalIdentity", localId, "LCGeneralSaveData");
					}
				}
				if (network.IsServer)
				{
					identities[network.LocalClientId] = localId;
				}
				else if (Time.unscaledTime >= nextIdentity && network.CustomMessagingManager != null)
				{
					nextIdentity = Time.unscaledTime + 3f;
					FastBufferWriter val3 = default(FastBufferWriter);
					((FastBufferWriter)(ref val3))..ctor(136, (Allocator)2, -1);
					try
					{
						((FastBufferWriter)(ref val3)).WriteValueSafe(localId, false);
						network.CustomMessagingManager.SendNamedMessage("Saltanis.Wallet/1/identity", 0uL, val3, (NetworkDelivery)3);
					}
					finally
					{
						((IDisposable)(*(FastBufferWriter*)(&val3))/*cast due to .constrained prefix*/).Dispose();
					}
				}
			}
			StartOfRound val4 = StartOfRound.Instance;
			if (!network.IsServer || !Object.op_Implicit((Object)(object)val4) || !val4.shipHasLanded || val4.shipIsLeaving || val4.inShipPhase || !Object.op_Implicit((Object)(object)val4.currentLevel) || val4.currentLevel.sceneName == "CompanyBuilding" || !val4.currentLevel.planetHasTime || !Ready())
			{
				return;
			}
			bool flag = false;
			PlayerControllerB[] allPlayerScripts = val4.allPlayerScripts;
			foreach (PlayerControllerB val5 in allPlayerScripts)
			{
				if (!Object.op_Implicit((Object)(object)val5) || !val5.isPlayerControlled || val5.isPlayerDead)
				{
					continue;
				}
				string text = Key(val5);
				if (text != null)
				{
					Account account = AccountFor(text);
					int timesFulfilledQuota = TimeOfDay.Instance.timesFulfilledQuota;
					if (account.LastParticipation != timesFulfilledQuota)
					{
						account.LastParticipation = timesFulfilledQuota;
						flag = true;
					}
				}
			}
			if (flag)
			{
				ES3.Save<string>("Saltanis.PersonalWallet.v1", JsonConvert.SerializeObject((object)ledger, JsonSettings), slot);
			}
		}

		private void Forget(ulong client)
		{
			identities.Remove(client);
		}

		private void Identity(ulong sender, FastBufferReader reader)
		{
			if (network.IsServer && network.ConnectedClients.ContainsKey(sender) && !identities.ContainsKey(sender) && ((FastBufferReader)(ref reader)).Length >= 4 && ((FastBufferReader)(ref reader)).Length <= 136)
			{
				string input = default(string);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref input, false);
				if (Guid.TryParseExact(input, "N", out var result) && !identities.ContainsValue(result.ToString("N")))
				{
					identities[sender] = result.ToString("N");
				}
			}
		}

		public static string Key(PlayerControllerB p)
		{
			if (!Object.op_Implicit((Object)(object)p))
			{
				return null;
			}
			if (p.playerSteamId != 0L)
			{
				return "steam:" + p.playerSteamId;
			}
			if (!Object.op_Implicit((Object)(object)instance) || !instance.identities.TryGetValue(p.actualClientId, out var value))
			{
				return null;
			}
			return "lan:" + value;
		}

		private bool Ready()
		{
			GameNetworkManager val = GameNetworkManager.Instance;
			StartOfRound val2 = StartOfRound.Instance;
			if (!Object.op_Implicit((Object)(object)network) || !network.IsServer || !Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val2) || val2.isChallengeFile || !Object.op_Implicit((Object)(object)TimeOfDay.Instance) || string.IsNullOrEmpty(val.currentSaveFileName))
			{
				return false;
			}
			if (slot == val.currentSaveFileName)
			{
				return this.ledger != null;
			}
			slot = val.currentSaveFileName;
			this.ledger = null;
			try
			{
				string text = ES3.Load<string>("Saltanis.PersonalWallet.v1", slot, (string)null);
				string text2 = text ?? ES3.Load<string>("saltanis.zabkowysklep.campaign.v1", slot, (string)null);
				Ledger ledger = ((text2 == null) ? new Ledger() : JsonConvert.DeserializeObject<Ledger>(text2, JsonSettings));
				if (ledger?.Wallets == null || ledger.Wallets.Any((Account a) => a == null || string.IsNullOrEmpty(a.Player) || a.Balance < 0) || (from a in ledger.Wallets
					group a by a.Player).Any((IGrouping<string, Account> g) => g.Count() != 1))
				{
					throw new FormatException("Invalid wallet data");
				}
				if (text == null && text2 != null)
				{
					ES3.Save<string>("Saltanis.PersonalWallet.v1", JsonConvert.SerializeObject((object)ledger, JsonSettings), slot);
				}
				this.ledger = ledger;
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("[Saltanis Wallet] " + ex));
			}
			return this.ledger != null;
		}

		private Account AccountFor(string key)
		{
			Account account = ledger.Wallets.Find((Account x) => x.Player == key);
			if (account == null)
			{
				account = new Account
				{
					Player = key
				};
				ledger.Wallets.Add(account);
			}
			return account;
		}

		public static long Balance(PlayerControllerB p)
		{
			string key = Key(p);
			if (key == null || !instance.Ready())
			{
				return 0L;
			}
			return instance.ledger.Wallets.Find((Account a) => a.Player == key)?.Balance ?? 0;
		}

		public static string[] ParticipatingAccounts(int cycle)
		{
			if (!IsActive)
			{
				return Array.Empty<string>();
			}
			return (from a in instance.ledger.Wallets
				where a.LastParticipation == cycle
				select a.Player).ToArray();
		}

		public static bool TryGrantBatch(string receipt, string[] players, long cents, string moduleSaveKey, string moduleJson)
		{
			if (string.IsNullOrEmpty(receipt) || receipt.Length > 200 || players == null || players.Length > 256 || cents <= 0 || cents > 100000000 || string.IsNullOrEmpty(moduleSaveKey) || moduleSaveKey == "Saltanis.PersonalWallet.v1" || string.IsNullOrEmpty(moduleJson) || !IsActive)
			{
				return false;
			}
			string[] array = players.Distinct().ToArray();
			if (array.Length == 0 || array.Any((string k) => string.IsNullOrEmpty(k) || k.Length > 150))
			{
				return false;
			}
			Ledger ledger = instance.ledger;
			if (ledger.RewardReceipts == null)
			{
				ledger.RewardReceipts = new List<string>();
			}
			if (ledger.RewardReceipts.Contains(receipt))
			{
				try
				{
					CommitPurchase(instance.slot, JsonConvert.SerializeObject((object)ledger, JsonSettings), moduleSaveKey, moduleJson);
					return true;
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("[Saltanis Wallet] " + ex));
					return false;
				}
			}
			Account[] array2 = array.Select(instance.AccountFor).ToArray();
			if (array2.Any((Account a) => a.Balance > long.MaxValue - cents))
			{
				return false;
			}
			Account[] array3 = array2;
			for (int num = 0; num < array3.Length; num++)
			{
				array3[num].Balance += cents;
			}
			ledger.RewardReceipts.Add(receipt);
			try
			{
				CommitPurchase(instance.slot, JsonConvert.SerializeObject((object)ledger, JsonSettings), moduleSaveKey, moduleJson);
			}
			catch (Exception ex2)
			{
				array3 = array2;
				for (int num = 0; num < array3.Length; num++)
				{
					array3[num].Balance -= cents;
				}
				ledger.RewardReceipts.Remove(receipt);
				Debug.LogError((object)("[Saltanis Wallet] " + ex2));
				return false;
			}
			Delegate[] array4 = CrewWallet.Paid?.GetInvocationList();
			if (array4 != null)
			{
				string[] array5 = array;
				foreach (string arg in array5)
				{
					Delegate[] array6 = array4;
					for (int num2 = 0; num2 < array6.Length; num2++)
					{
						Action<string, long> action = (Action<string, long>)array6[num2];
						try
						{
							action(arg, cents);
						}
						catch (Exception ex3)
						{
							Debug.LogError((object)("[Saltanis Wallet] " + ex3));
						}
					}
				}
			}
			return true;
		}

		public static bool TryPurchase(PlayerControllerB player, long cents, string moduleSaveKey, string moduleJson)
		{
			string text = Key(player);
			if (text == null || cents <= 0 || string.IsNullOrEmpty(moduleSaveKey) || moduleSaveKey == "Saltanis.PersonalWallet.v1" || string.IsNullOrEmpty(moduleJson) || !instance.Ready())
			{
				return false;
			}
			Account account = instance.AccountFor(text);
			if (account.Balance < cents)
			{
				return false;
			}
			account.Balance -= cents;
			try
			{
				CommitPurchase(instance.slot, JsonConvert.SerializeObject((object)instance.ledger, JsonSettings), moduleSaveKey, moduleJson);
				return true;
			}
			catch (Exception ex)
			{
				account.Balance += cents;
				Debug.LogError((object)("[Saltanis Wallet] " + ex));
				return false;
			}
		}

		private static void CommitPurchase(string path, string walletJson, string moduleKey, string moduleJson)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			ES3File value = null;
			bool flag = ES3File.cachedFiles != null && ES3File.cachedFiles.TryGetValue(path, out value);
			if (!flag)
			{
				value = new ES3File(path);
			}
			string text = (flag ? value.Load<string>("Saltanis.PersonalWallet.v1", (string)null) : null);
			string text2 = (flag ? value.Load<string>(moduleKey, (string)null) : null);
			try
			{
				value.Save<string>("Saltanis.PersonalWallet.v1", walletJson);
				value.Save<string>(moduleKey, moduleJson);
				value.Sync(new ES3Settings(path, (ES3Settings)null)
				{
					location = (Location)0
				});
			}
			catch
			{
				if (flag)
				{
					if (text == null)
					{
						value.DeleteKey("Saltanis.PersonalWallet.v1");
					}
					else
					{
						value.Save<string>("Saltanis.PersonalWallet.v1", text);
					}
					if (text2 == null)
					{
						value.DeleteKey(moduleKey);
					}
					else
					{
						value.Save<string>(moduleKey, text2);
					}
				}
				throw;
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager), "ResetSavedGameValues")]
		[HarmonyPostfix]
		private static void Reset()
		{
			GameNetworkManager val = GameNetworkManager.Instance;
			if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)NetworkManager.Singleton) && NetworkManager.Singleton.IsServer && Object.op_Implicit((Object)(object)val) && !string.IsNullOrEmpty(val.currentSaveFileName) && Object.op_Implicit((Object)(object)StartOfRound.Instance) && !StartOfRound.Instance.isChallengeFile)
			{
				ES3.Save<string>("Saltanis.PersonalWallet.v1", JsonConvert.SerializeObject((object)new Ledger(), JsonSettings), val.currentSaveFileName);
				instance.slot = null;
				instance.ledger = null;
			}
		}

		private static int Supplemental(DepositItemsDesk desk)
		{
			return SupplementalSaleValue?.Invoke(desk) ?? 0;
		}

		internal static void Sale(int credits, int supplemental)
		{
			if (!Object.op_Implicit((Object)(object)instance) || credits <= 0 || !instance.Ready() || StartOfRound.Instance.currentLevel?.sceneName != "CompanyBuilding")
			{
				return;
			}
			int timesFulfilledQuota = TimeOfDay.Instance.timesFulfilledQuota;
			Dictionary<string, long> dictionary = new Dictionary<string, long>();
			foreach (Account wallet in instance.ledger.Wallets)
			{
				if (wallet.LastParticipation == timesFulfilledQuota)
				{
					dictionary[wallet.Player] = 5L * (long)credits;
				}
			}
			long num = 5L * (long)Mathf.Clamp((int)((float)supplemental * StartOfRound.Instance.companyBuyingRate), 0, credits);
			if (num > 0)
			{
				PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
				foreach (PlayerControllerB val in allPlayerScripts)
				{
					if (Object.op_Implicit((Object)(object)val) && (val.isPlayerControlled || val.isPlayerDead) && instance.network.ConnectedClients.ContainsKey(val.actualClientId))
					{
						string text = Key(val);
						if (text != null && !dictionary.ContainsKey(text))
						{
							dictionary[text] = num;
						}
					}
				}
			}
			if (dictionary.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<string, long> item in dictionary)
			{
				instance.AccountFor(item.Key).Balance += item.Value;
			}
			try
			{
				ES3.Save<string>("Saltanis.PersonalWallet.v1", JsonConvert.SerializeObject((object)instance.ledger, JsonSettings), instance.slot);
			}
			catch (Exception ex)
			{
				foreach (KeyValuePair<string, long> item2 in dictionary)
				{
					instance.AccountFor(item2.Key).Balance -= item2.Value;
				}
				Debug.LogError((object)("[Saltanis Wallet] Could not save sale payout: " + ex));
				return;
			}
			foreach (KeyValuePair<string, long> item3 in dictionary)
			{
				CrewWallet.Paid?.Invoke(item3.Key, item3.Value);
			}
		}

		[HarmonyPatch(typeof(DepositItemsDesk), "SellItemsOnServer")]
		[HarmonyTranspiler]
		[HarmonyPriority(0)]
		private static IEnumerable<CodeInstruction> ObserveSale(IEnumerable<CodeInstruction> original, ILGenerator il)
		{
			MethodInfo display = AccessTools.Method(typeof(DepositItemsDesk), "SellAndDisplayItemProfits", (Type[])null, (Type[])null);
			LocalBuilder profit = il.DeclareLocal(typeof(int));
			LocalBuilder newCredits = il.DeclareLocal(typeof(int));
			LocalBuilder extra = il.DeclareLocal(typeof(int));
			foreach (CodeInstruction op in original)
			{
				if (!CodeInstructionExtensions.Calls(op, display))
				{
					yield return op;
					continue;
				}
				yield return CodeInstructionExtensions.MoveBlocksFrom(CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Stloc, (object)newCredits), op), op);
				yield return new CodeInstruction(OpCodes.Dup, (object)null);
				yield return new CodeInstruction(OpCodes.Stloc, (object)profit);
				yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
				yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(CrewWallet), "Supplemental", (Type[])null, (Type[])null));
				yield return new CodeInstruction(OpCodes.Stloc, (object)extra);
				yield return new CodeInstruction(OpCodes.Ldloc, (object)newCredits);
				yield return op;
				yield return new CodeInstruction(OpCodes.Ldloc, (object)profit);
				yield return new CodeInstruction(OpCodes.Ldloc, (object)extra);
				yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(CrewWallet), "Sale", (Type[])null, (Type[])null));
			}
		}
	}
	public sealed class WalletHud
	{
		private readonly Func<long, string> format;

		private readonly Func<string> receiptFormat;

		private static readonly string[] WalletPixels = new string[16]
		{
			"................", "....#######.....", "...#.......#....", "..#.........#...", ".#############..", ".#...........#..", ".#...........#..", ".#.......######.", ".#......##....#.", ".#......#..##.#.",
			".#......##....#.", ".#.......######.", ".#...........#..", ".#...........#..", ".#############..", "................"
		};

		private RectTransform root;

		private TextMeshProUGUI attachedKey;

		private TextMeshProUGUI amount;

		private TextMeshProUGUI receipt;

		private Texture2D walletTexture;

		private long displayedBalance = -1L;

		private string payoutMessage;

		private float receiptUntil;

		public WalletHud(Func<long, string> format, Func<string> receiptFormat)
		{
			this.format = format;
			this.receiptFormat = receiptFormat;
		}

		public void RecordPayout(long value)
		{
			payoutMessage = string.Format(receiptFormat(), format(value));
			receiptUntil = Time.unscaledTime + 6f;
			if (Object.op_Implicit((Object)(object)receipt))
			{
				((TMP_Text)receipt).text = payoutMessage;
			}
		}

		public void Clear()
		{
			payoutMessage = string.Empty;
			receiptUntil = 0f;
			if (Object.op_Implicit((Object)(object)root))
			{
				((Component)root).gameObject.SetActive(false);
			}
		}

		public void Dispose()
		{
			if (Object.op_Implicit((Object)(object)root))
			{
				Object.Destroy((Object)(object)((Component)root).gameObject);
			}
			if (Object.op_Implicit((Object)(object)walletTexture))
			{
				Object.Destroy((Object)(object)walletTexture);
			}
		}

		public void Update(PlayerControllerB player, long balance)
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//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)
			HUDManager instance = HUDManager.Instance;
			if (!Object.op_Implicit((Object)(object)player) || player.isPlayerDead || !player.isPlayerControlled || player.inTerminalMenu || !Object.op_Implicit((Object)(object)instance) || (Object.op_Implicit((Object)(object)player.quickMenuManager) && player.quickMenuManager.isMenuOpen) || !Object.op_Implicit((Object)(object)instance.utilitySlotKeyText))
			{
				if (Object.op_Implicit((Object)(object)root))
				{
					((Component)root).gameObject.SetActive(false);
				}
				return;
			}
			TextMeshProUGUI utilitySlotKeyText = instance.utilitySlotKeyText;
			RectTransform rectTransform = ((TMP_Text)utilitySlotKeyText).rectTransform;
			if (!Object.op_Implicit((Object)(object)root) || (Object)(object)attachedKey != (Object)(object)utilitySlotKeyText || (Object)(object)((Transform)root).parent != (Object)(object)((Transform)rectTransform).parent)
			{
				Attach(utilitySlotKeyText);
			}
			Bounds textBounds = ((TMP_Text)utilitySlotKeyText).textBounds;
			bool num = ((Bounds)(ref textBounds)).size.x > 0f;
			Rect rect;
			float num2;
			if (!num)
			{
				rect = rectTransform.rect;
				num2 = ((Rect)(ref rect)).xMax;
			}
			else
			{
				num2 = ((Bounds)(ref textBounds)).max.x;
			}
			float num3 = num2;
			float y;
			if (!num)
			{
				rect = rectTransform.rect;
				y = ((Rect)(ref rect)).center.y;
			}
			else
			{
				y = ((Bounds)(ref textBounds)).center.y;
			}
			float num4 = y;
			((Transform)root).position = ((Transform)rectTransform).TransformPoint(new Vector3(num3 + ((TMP_Text)utilitySlotKeyText).fontSize * 1.2f, num4));
			((Component)root).gameObject.SetActive(true);
			if (displayedBalance != balance)
			{
				displayedBalance = balance;
				((TMP_Text)amount).text = format(balance);
			}
			((Component)receipt).gameObject.SetActive(Time.unscaledTime < receiptUntil);
		}

		private void Attach(TextMeshProUGUI style)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: 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_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)root))
			{
				Object.Destroy((Object)(object)((Component)root).gameObject);
			}
			attachedKey = style;
			RectTransform rectTransform = ((TMP_Text)style).rectTransform;
			root = new GameObject("Bummer Mart wallet", new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>();
			((Transform)root).SetParent(((Transform)rectTransform).parent, false);
			((Transform)root).localRotation = ((Transform)rectTransform).localRotation;
			((Transform)root).localScale = ((Transform)rectTransform).localScale;
			root.sizeDelta = Vector2.zero;
			float fontSize = ((TMP_Text)style).fontSize;
			float num = fontSize * 1.45f;
			RawImage component = new GameObject("Wallet icon", new Type[2]
			{
				typeof(RectTransform),
				typeof(RawImage)
			}).GetComponent<RawImage>();
			component.texture = (Texture)(object)GetWalletTexture();
			((Graphic)component).color = ((Graphic)style).color;
			((Graphic)component).raycastTarget = false;
			Layout(((Graphic)component).rectTransform, Vector2.zero, new Vector2(num, num));
			float num2 = num + fontSize * 0.38f;
			amount = CreateText("Balance", style, new Vector2(num2, 0f), fontSize);
			receipt = CreateText("Payout", style, new Vector2(0f, (0f - fontSize) * 1.3f), fontSize);
			((TMP_Text)receipt).fontSize = ((TMP_Text)style).fontSize * 0.82f;
			((TMP_Text)receipt).text = payoutMessage;
			displayedBalance = -1L;
		}

		private TextMeshProUGUI CreateText(string name, TextMeshProUGUI style, Vector2 position, float unit)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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)
			TextMeshProUGUI component = new GameObject(name, new Type[2]
			{
				typeof(RectTransform),
				typeof(TextMeshProUGUI)
			}).GetComponent<TextMeshProUGUI>();
			((TMP_Text)component).font = ((TMP_Text)style).font;
			((TMP_Text)component).fontSharedMaterial = ((TMP_Text)style).fontSharedMaterial;
			((TMP_Text)component).fontSize = ((TMP_Text)style).fontSize;
			((TMP_Text)component).fontStyle = ((TMP_Text)style).fontStyle;
			((Graphic)component).color = ((Graphic)style).color;
			((TMP_Text)component).alignment = (TextAlignmentOptions)4097;
			((Graphic)component).raycastTarget = false;
			Layout(((TMP_Text)component).rectTransform, position, new Vector2(unit * 17f, unit * 1.45f));
			return component;
		}

		private void Layout(RectTransform element, Vector2 position, Vector2 size)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			((Transform)element).SetParent((Transform)(object)root, false);
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(0.5f, 0.5f);
			element.anchorMax = val;
			element.anchorMin = val;
			element.pivot = new Vector2(0f, 0.5f);
			element.anchoredPosition = position;
			element.sizeDelta = size;
		}

		private Texture2D GetWalletTexture()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: 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_0097: Expected O, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)walletTexture))
			{
				return walletTexture;
			}
			int num = WalletPixels.Length;
			Color32[] array = (Color32[])(object)new Color32[num * num];
			Color32 val = Color32.op_Implicit(Color.white);
			for (int i = 0; i < num; i++)
			{
				for (int j = 0; j < num; j++)
				{
					if (WalletPixels[i][j] == '#')
					{
						array[(num - 1 - i) * num + j] = val;
					}
				}
			}
			walletTexture = new Texture2D(num, num, (TextureFormat)4, false)
			{
				name = "Bummer Mart wallet icon",
				filterMode = (FilterMode)0,
				wrapMode = (TextureWrapMode)1
			};
			walletTexture.SetPixels32(array);
			walletTexture.Apply(false, true);
			return walletTexture;
		}
	}
}