Decompiled source of Separate Wallets v0.4.2

BepInEx/plugins/SeparateWallets/SeparateWallets.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Mirror;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SeparateWallets")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.2.0")]
[assembly: AssemblyInformationalVersion("0.4.2")]
[assembly: AssemblyProduct("SeparateWallets")]
[assembly: AssemblyTitle("SeparateWallets")]
[assembly: AssemblyVersion("0.4.2.0")]
namespace SeparateWallets;

internal static class Calls
{
	internal static IEnumerable<CodeInstruction> Replace(IEnumerable<CodeInstruction> code, MethodInfo original, MethodInfo replacement, int expected = 1)
	{
		int matches = 0;
		foreach (CodeInstruction item in code)
		{
			if (CodeInstructionExtensions.Calls(item, original))
			{
				item.opcode = OpCodes.Call;
				item.operand = replacement;
				matches++;
			}
			yield return item;
		}
		if (matches != expected)
		{
			throw new InvalidOperationException($"Expected {expected} call(s) to {original.Name}, found {matches}.");
		}
	}
}
[HarmonyPatch]
internal static class AccountLookup
{
	private static readonly MethodInfo Key = AccessTools.Method(typeof(FinanceManager), "AccountKey", (Type[])null, (Type[])null);

	private static readonly Func<ulong, ulong> NativeKey = (Func<ulong, ulong>)Delegate.CreateDelegate(typeof(Func<ulong, ulong>), Key);

	private static IEnumerable<MethodBase> TargetMethods()
	{
		yield return AccessTools.Method(typeof(FinanceManager), "GetAccount", (Type[])null, (Type[])null);
		yield return AccessTools.Method(typeof(FinanceManager), "GetOrCreateAccount", (Type[])null, (Type[])null);
	}

	private static ulong AccountFor(ulong id)
	{
		if (!GameMode.IsIncremental)
		{
			return NativeKey(id);
		}
		return id;
	}

	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		return Calls.Replace(instructions, Key, AccessTools.Method(typeof(AccountLookup), "AccountFor", (Type[])null, (Type[])null));
	}
}
[HarmonyPatch(typeof(FinanceManager), "ServerTransfer")]
internal static class TransferGuard
{
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		return Calls.Replace(instructions, AccessTools.PropertyGetter(typeof(GameMode), "IsIncremental"), AccessTools.Method(typeof(Wallets), "SharedTransferGuard", (Type[])null, (Type[])null));
	}
}
[HarmonyPatch(typeof(FinanceManager), "PublishBalance")]
internal static class PublishPersonalBalance
{
	private static bool Prefix(PlayerAccount account)
	{
		if (GameMode.IsIncremental && account != null)
		{
			return account.steamId != ulong.MaxValue;
		}
		return true;
	}
}
[HarmonyPatch(typeof(FinanceManager), "Credit")]
internal static class Credit
{
	private static bool Prefix(FinanceManager __instance, ref ulong steamId, int amount, ref string displayName, string reason, bool notifyClient)
	{
		return Wallets.RouteCredit(__instance, ref steamId, amount, ref displayName, reason, notifyClient);
	}
}
internal static class Origins
{
	internal sealed class Seller
	{
		internal readonly PlayerController Controller;

		internal readonly ulong Id;

		internal readonly string Name;

		internal Seller(PlayerController player)
		{
			Controller = player;
			Id = player.steamId;
			Name = Wallets.Display(player);
		}
	}

	internal static readonly ConditionalWeakTable<HeldItem, Seller> Drops = new ConditionalWeakTable<HeldItem, Seller>();

	[ThreadStatic]
	internal static int Automation;

	[ThreadStatic]
	internal static Seller RecycleSeller;

	internal static bool TrySeller(ulong id, string name, string reason, out ulong payee, out string seller)
	{
		payee = id;
		seller = name;
		if (Automation != 0)
		{
			return false;
		}
		if (HasKey(reason, "Reason_Recycled"))
		{
			if (RecycleSeller == null)
			{
				return false;
			}
			payee = RecycleSeller.Id;
			seller = RecycleSeller.Name;
			return true;
		}
		if (Wallets.PersonalId(id))
		{
			switch (reason)
			{
			default:
				return HasKey(reason, "Reason_BotSold");
			case "Reason_CashIn":
			case "Reason_Deposit_Payout":
			case "Reason_Shredder_Payout":
				return true;
			}
		}
		return false;
	}

	private static bool HasKey(string reason, string key)
	{
		if (!(reason == key))
		{
			return reason?.StartsWith(key + "\u001f", StringComparison.Ordinal) ?? false;
		}
		return true;
	}
}
[HarmonyPatch]
internal static class AutomaticCollectorPayout
{
	private static IEnumerable<MethodBase> TargetMethods()
	{
		yield return AccessTools.Method(typeof(CollectorDepot), "ServerPayMine", (Type[])null, (Type[])null);
		yield return AccessTools.Method(typeof(IncrementalCollector), "Unreachable", (Type[])null, (Type[])null);
	}

	private static void Prefix(out int __state)
	{
		__state = Origins.Automation;
		Origins.Automation++;
	}

	private static void Finalizer(int __state)
	{
		Origins.Automation = __state;
	}
}
[HarmonyPatch(typeof(HeldItem), "Drop", new Type[] { typeof(Vector3) })]
internal static class RememberDropper
{
	private static void Prefix(HeldItem __instance)
	{
		if (!NetworkServer.active || !GameMode.IsIncremental)
		{
			return;
		}
		Origins.Drops.Remove(__instance);
		if (!((Object)(object)__instance.Holder == (Object)null))
		{
			Player player = __instance.Holder.Player;
			PlayerController val = (((Object)(object)player != (Object)null) ? player.playerController : null);
			if ((Object)(object)val != (Object)null && Wallets.PersonalId(val.steamId))
			{
				Origins.Drops.Add(__instance, new Origins.Seller(val));
			}
		}
	}
}
[HarmonyPatch(typeof(ToolRecycler), "ServerTake")]
internal static class RecyclerSource
{
	private static void Prefix(HeldItem item, ref PlayerController payee, out Origins.Seller __state)
	{
		__state = null;
		if (GameMode.IsIncremental && (Object)(object)item != (Object)null && Origins.Drops.TryGetValue(item, out __state) && (Object)(object)__state.Controller != (Object)null)
		{
			payee = __state.Controller;
		}
	}

	private static void Postfix(Origins.Seller __state, ref IEnumerator __result)
	{
		if (GameMode.IsIncremental && __result != null)
		{
			__result = Run(__result, __state);
		}
	}

	private static IEnumerator Run(IEnumerator inner, Origins.Seller owner)
	{
		try
		{
			while (true)
			{
				Origins.Seller recycleSeller = Origins.RecycleSeller;
				bool flag;
				try
				{
					Origins.RecycleSeller = owner;
					flag = inner.MoveNext();
				}
				finally
				{
					Origins.RecycleSeller = recycleSeller;
				}
				if (flag)
				{
					yield return inner.Current;
					continue;
				}
				break;
			}
		}
		finally
		{
			(inner as IDisposable)?.Dispose();
		}
	}
}
[HarmonyPatch(typeof(IncrementalFreeTools), "CrewMoney")]
internal static class RescueBudget
{
	private static bool Prefix(ref int __result)
	{
		if (!GameMode.IsIncremental || !NetworkServer.active)
		{
			return true;
		}
		int num = Wallets.CrewCash();
		__result = ((num != 0) ? Math.Min(num, int.MaxValue - Math.Max(0, IncrementalTank.ServerAllTanksCents())) : 0);
		return false;
	}
}
[HarmonyPatch(typeof(SaveManager), "BuildSlotMeta")]
internal static class SlotPreview
{
	private static void Postfix(FinanceSaveData finance, SlotSaveMeta __result)
	{
		if (!GameMode.IsIncremental || __result == null || finance?.accounts == null)
		{
			return;
		}
		long num = 0L;
		foreach (PlayerAccount account in finance.accounts)
		{
			if (account != null)
			{
				num += account.balance;
			}
		}
		__result.balanceCents = (int)Math.Max(0L, Math.Min(2147483647L, num));
	}
}
[HarmonyPatch]
internal static class PersonalHudGains
{
	private static IEnumerable<MethodBase> TargetMethods()
	{
		string[] array = new string[3] { "OnMySaleSending", "OnCashedIn", "OnBonus" };
		foreach (string text in array)
		{
			yield return AccessTools.Method(typeof(IncrementalStatusHud), text, (Type[])null, (Type[])null);
		}
	}

	private static bool Prefix()
	{
		if (GameMode.IsIncremental)
		{
			return !Wire.HostSupportsWallets;
		}
		return true;
	}
}
[Serializable]
public sealed class FreeBudgetAllowance
{
	public ulong playerId;

	public int percent;

	public int cents;

	public int hundredths;
}
internal sealed class BudgetMove
{
	internal bool MarkedFirst;

	internal bool FromReserve;

	internal int Sent;

	internal int Received;

	internal int MarkedSpent;

	internal int RestoreOnReceipt;
}
internal static class FreeBudget
{
	internal const int DefaultPercent = 10;

	private static readonly ConditionalWeakTable<PlayerAccount, FreeBudgetAllowance> allowances = new ConditionalWeakTable<PlayerAccount, FreeBudgetAllowance>();

	internal static FreeBudgetAllowance For(PlayerAccount account)
	{
		return allowances.GetValue(account, (PlayerAccount a) => new FreeBudgetAllowance
		{
			playerId = a.steamId,
			percent = ((a.steamId == ulong.MaxValue) ? 100 : 10)
		});
	}

	internal static int Marked(PlayerAccount account)
	{
		if (account == null || !allowances.TryGetValue(account, out var value))
		{
			return 0;
		}
		return Math.Min(value.cents, Math.Max(0, account.balance));
	}

	internal static void SetPercent(PlayerAccount account, int percent)
	{
		if (account != null && Wallets.PersonalId(account.steamId) && percent >= 0 && percent <= 100)
		{
			For(account).percent = percent;
		}
	}

	internal static void ReleaseHoldings(PlayerAccount account)
	{
		if (account != null && Wallets.PersonalId(account.steamId))
		{
			FreeBudgetAllowance freeBudgetAllowance = For(account);
			freeBudgetAllowance.cents = 0;
			freeBudgetAllowance.hundredths = 0;
		}
	}

	internal static void Earn(PlayerAccount account, int income)
	{
		if (income > 0)
		{
			FreeBudgetAllowance freeBudgetAllowance = For(account);
			long num = (long)income * (long)freeBudgetAllowance.percent + freeBudgetAllowance.hundredths;
			freeBudgetAllowance.cents = (int)Math.Min(account.balance, freeBudgetAllowance.cents + num / 100);
			freeBudgetAllowance.hundredths = (int)(num % 100);
		}
	}

	internal static void Spent(PlayerAccount account, int previousBalance, BudgetMove receipt)
	{
		int num = previousBalance - account.balance;
		int markedSpent = 0;
		if (allowances.TryGetValue(account, out var value))
		{
			int num2 = Math.Min(value.cents, previousBalance);
			value.cents = ((receipt != null && receipt.MarkedFirst) ? Math.Max(0, num2 - num) : Math.Min(num2, account.balance));
			markedSpent = num2 - value.cents;
		}
		if (receipt != null)
		{
			receipt.Sent = num;
			receipt.MarkedSpent = markedSpent;
			receipt.FromReserve = account.steamId == ulong.MaxValue;
		}
	}

	internal static void Received(PlayerAccount account, int amount, BudgetMove receipt)
	{
		if (receipt != null)
		{
			receipt.Received = amount;
			if (receipt.FromReserve)
			{
				Earn(account, Math.Min(amount, receipt.MarkedSpent));
			}
			if (receipt.RestoreOnReceipt > 0)
			{
				FreeBudgetAllowance freeBudgetAllowance = For(account);
				freeBudgetAllowance.cents = (int)Math.Min(account.balance, (long)freeBudgetAllowance.cents + (long)Math.Min(amount, receipt.RestoreOnReceipt));
			}
		}
	}

	internal static bool TryPlan(FinanceManager finance, ulong buyer, int gap, Dictionary<ulong, int> payments, ulong previousExtra, out ulong nextExtra)
	{
		nextExtra = previousExtra;
		List<PlayerController> list = Wallets.CrewOnline();
		int[] array = new int[list.Count];
		int start = 0;
		for (int i = 0; i < list.Count; i++)
		{
			PlayerController val = list[i];
			if (val.steamId <= previousExtra)
			{
				start = i + 1;
			}
			if (val.steamId != buyer && FreeBudgetNet.CanContribute(val))
			{
				array[i] = Marked(finance.GetAccount(val.steamId));
			}
		}
		int[] array2 = new int[list.Count];
		if (MoneyRules.DivideByCapacity(gap, array, start, array2, out var lastExtra) != 0)
		{
			return false;
		}
		for (int j = 0; j < array2.Length; j++)
		{
			if (array2[j] > 0)
			{
				payments.Add(list[j].steamId, array2[j]);
			}
		}
		if (lastExtra >= 0)
		{
			nextExtra = list[lastExtra].steamId;
		}
		return true;
	}

	internal static FreeBudgetAllowance[] Capture(FinanceSaveData finance)
	{
		List<FreeBudgetAllowance> list = new List<FreeBudgetAllowance>();
		if (finance?.accounts != null)
		{
			foreach (PlayerAccount account in finance.accounts)
			{
				if (account != null && allowances.TryGetValue(account, out var value))
				{
					list.Add(new FreeBudgetAllowance
					{
						playerId = account.steamId,
						percent = value.percent,
						cents = Marked(account),
						hundredths = value.hundredths
					});
				}
			}
		}
		return list.ToArray();
	}

	internal static void Restore(FinanceSaveData finance, FreeBudgetAllowance[] rows)
	{
		if (rows == null || finance?.accounts == null)
		{
			return;
		}
		Dictionary<ulong, PlayerAccount> dictionary = new Dictionary<ulong, PlayerAccount>();
		foreach (PlayerAccount account in finance.accounts)
		{
			if (account != null && account.steamId != 0L)
			{
				dictionary[account.steamId] = account;
			}
		}
		foreach (FreeBudgetAllowance freeBudgetAllowance in rows)
		{
			if (freeBudgetAllowance != null && dictionary.TryGetValue(freeBudgetAllowance.playerId, out var value) && freeBudgetAllowance.percent >= 0 && freeBudgetAllowance.percent <= 100)
			{
				FreeBudgetAllowance freeBudgetAllowance2 = For(value);
				freeBudgetAllowance2.percent = ((value.steamId == ulong.MaxValue) ? 100 : freeBudgetAllowance.percent);
				freeBudgetAllowance2.cents = Math.Max(0, Math.Min(value.balance, freeBudgetAllowance.cents));
				freeBudgetAllowance2.hundredths = Math.Min(99, Math.Max(0, freeBudgetAllowance.hundredths));
			}
		}
	}
}
[HarmonyPatch]
internal static class FreeBudgetBalanceWrites
{
	private static readonly MethodInfo Setter = AccessTools.Method(typeof(FinanceManager), "SetBalance", (Type[])null, (Type[])null);

	private static readonly Action<FinanceManager, PlayerAccount, int> SetBalance = (Action<FinanceManager, PlayerAccount, int>)Delegate.CreateDelegate(typeof(Action<FinanceManager, PlayerAccount, int>), Setter);

	private static IEnumerable<MethodBase> TargetMethods()
	{
		yield return AccessTools.Method(typeof(FinanceManager), "Credit", (Type[])null, (Type[])null);
		yield return AccessTools.Method(typeof(FinanceManager), "Debit", (Type[])null, (Type[])null);
		yield return AccessTools.Method(typeof(FinanceManager), "ServerTransfer", (Type[])null, (Type[])null);
	}

	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
	{
		bool flag = __originalMethod.Name == "ServerTransfer";
		MethodInfo replacement = AccessTools.Method(typeof(FreeBudgetBalanceWrites), flag ? "Transfer" : "Transaction", (Type[])null, (Type[])null);
		return Calls.Replace(instructions, Setter, replacement, (!flag) ? 1 : 2);
	}

	internal static void Transaction(FinanceManager finance, PlayerAccount account, int cents)
	{
		int balance = account.balance;
		SetBalance(finance, account, cents);
		if (GameMode.IsIncremental && NetworkServer.active)
		{
			if (cents > balance)
			{
				FreeBudget.Earn(account, cents - balance);
			}
			else if (cents < balance)
			{
				FreeBudget.Spent(account, balance, null);
			}
		}
	}

	internal static void Transfer(FinanceManager finance, PlayerAccount account, int cents)
	{
		int balance = account.balance;
		SetBalance(finance, account, cents);
		if (GameMode.IsIncremental && NetworkServer.active)
		{
			if (cents < balance)
			{
				FreeBudget.Spent(account, balance, Wallets.Receipt);
			}
			else if (cents > balance)
			{
				FreeBudget.Received(account, cents - balance, Wallets.Receipt);
			}
		}
	}
}
internal struct FreeBudgetRate : NetworkMessage
{
	internal byte Percent;
}
[StructLayout(LayoutKind.Sequential, Size = 1)]
internal struct FreeBudgetRelease : NetworkMessage
{
}
internal struct FreeBudgetState : NetworkMessage
{
	internal byte Percent;

	internal int Marked;

	internal bool Reply;
}
internal static class FreeBudgetNet
{
	private sealed class Peer
	{
		internal ulong Id;

		internal int LastPercent = -1;

		internal int LastMarked = -1;

		internal bool OwesReply;
	}

	internal const string Probe = "SeparateWallets/free-budget/2?";

	private static readonly Dictionary<NetworkConnectionToClient, Peer> peers = new Dictionary<NetworkConnectionToClient, Peer>();

	private static float nextProbe;

	private static int probes;

	internal static bool Ready { get; private set; }

	internal static int PendingRate { get; private set; } = -1;

	internal static bool PendingRelease { get; private set; }

	internal static bool Waiting
	{
		get
		{
			if (PendingRate < 0)
			{
				return PendingRelease;
			}
			return true;
		}
	}

	internal static string Feedback { get; private set; } = "";

	internal static FreeBudgetState View { get; private set; }

	internal static void Codecs()
	{
		Writer<FreeBudgetRate>.write = delegate(NetworkWriter w, FreeBudgetRate m)
		{
			w.WriteByte(m.Percent);
		};
		Reader<FreeBudgetRate>.read = (NetworkReader r) => new FreeBudgetRate
		{
			Percent = r.ReadByte()
		};
		Writer<FreeBudgetRelease>.write = delegate
		{
		};
		Reader<FreeBudgetRelease>.read = (NetworkReader r) => default(FreeBudgetRelease);
		Writer<FreeBudgetState>.write = delegate(NetworkWriter w, FreeBudgetState m)
		{
			w.WriteByte(m.Percent);
			NetworkWriterExtensions.WriteInt(w, m.Marked);
			NetworkWriterExtensions.WriteBool(w, m.Reply);
		};
		Reader<FreeBudgetState>.read = (NetworkReader r) => new FreeBudgetState
		{
			Percent = r.ReadByte(),
			Marked = NetworkReaderExtensions.ReadInt(r),
			Reply = NetworkReaderExtensions.ReadBool(r)
		};
	}

	internal static void StartServer()
	{
		NetworkServer.ReplaceHandler<FreeBudgetRate>((Action<NetworkConnectionToClient, FreeBudgetRate>)SetRate, true);
		NetworkServer.ReplaceHandler<FreeBudgetRelease>((Action<NetworkConnectionToClient, FreeBudgetRelease>)Release, true);
	}

	internal static void StopServer()
	{
		peers.Clear();
	}

	internal static void Leave(NetworkConnectionToClient c)
	{
		peers.Remove(c);
	}

	internal static void StartClient()
	{
		NetworkClient.ReplaceHandler<FreeBudgetState>((Action<FreeBudgetState>)Receive, true);
	}

	internal static void ResetClient()
	{
		Ready = false;
		PendingRate = -1;
		PendingRelease = false;
		Feedback = "";
		View = default(FreeBudgetState);
		nextProbe = 0f;
		probes = 0;
	}

	internal static void TickClient()
	{
		if (!Ready && FundingNet.Ready && probes < 5 && !(Time.unscaledTime < nextProbe) && NetworkClient.ready && !((Object)(object)FinanceManager.instance == (Object)null) && NetworkClient.spawned.ContainsKey(((NetworkBehaviour)FinanceManager.instance).netId))
		{
			probes++;
			nextProbe = Time.unscaledTime + 3f;
			FinanceManager.instance.CmdRequestAccount(ulong.MaxValue, "SeparateWallets/free-budget/2?", (NetworkConnectionToClient)null);
		}
	}

	private static bool OwnsWallet(NetworkConnectionToClient c, out PlayerController player)
	{
		if (Wallets.Eligible(c, out player) && player.balanceKnown && FundingNet.Participants.TryGetValue(c, out var value) && value == player.steamId)
		{
			ulong num = default(ulong);
			if (MyNetworkManager.TryGetSteamId(c, ref num))
			{
				return num == value;
			}
			return true;
		}
		return false;
	}

	internal static bool CanContribute(PlayerController player)
	{
		NetworkIdentity netIdentity = ((NetworkBehaviour)player).netIdentity;
		NetworkConnectionToClient val = ((netIdentity != null) ? netIdentity.connectionToClient : null);
		if (val != null && peers.TryGetValue(val, out var value) && value.Id == player.steamId && OwnsWallet(val, out var player2))
		{
			return (Object)(object)player2 == (Object)(object)player;
		}
		return false;
	}

	internal static void Join(NetworkConnectionToClient c)
	{
		if (OwnsWallet(c, out var player))
		{
			Peer peer = new Peer
			{
				Id = player.steamId
			};
			peers[c] = peer;
			Push(c, peer);
		}
	}

	internal static void SetRate(NetworkConnectionToClient c, FreeBudgetRate m)
	{
		if (c == null || !peers.TryGetValue(c, out var value))
		{
			return;
		}
		value.OwesReply = true;
		if (GameMode.IsIncremental && OwnsWallet(c, out var player) && value.Id == player.steamId)
		{
			if (m.Percent <= 100 && !SaveManager.LoadInProgress && !IncrementalEggSwap.ServerSwapping)
			{
				FinanceManager instance = FinanceManager.instance;
				FreeBudget.SetPercent((instance != null) ? instance.GetAccount(player.steamId) : null, m.Percent);
			}
			Push(c, value);
		}
	}

	internal static void Release(NetworkConnectionToClient c, FreeBudgetRelease message)
	{
		if (c == null || !peers.TryGetValue(c, out var value))
		{
			return;
		}
		value.OwesReply = true;
		if (GameMode.IsIncremental && OwnsWallet(c, out var player) && value.Id == player.steamId)
		{
			if (!SaveManager.LoadInProgress && !IncrementalEggSwap.ServerSwapping)
			{
				FinanceManager instance = FinanceManager.instance;
				FreeBudget.ReleaseHoldings((instance != null) ? instance.GetAccount(player.steamId) : null);
			}
			Push(c, value);
		}
	}

	internal static void Sync()
	{
		foreach (KeyValuePair<NetworkConnectionToClient, Peer> peer in peers)
		{
			if (OwnsWallet(peer.Key, out var player) && player.steamId == peer.Value.Id)
			{
				Push(peer.Key, peer.Value);
			}
		}
	}

	private static void Push(NetworkConnectionToClient c, Peer peer)
	{
		FinanceManager instance = FinanceManager.instance;
		PlayerAccount val = ((instance != null) ? instance.GetAccount(peer.Id) : null);
		if (val != null)
		{
			int percent = FreeBudget.For(val).percent;
			int num = FreeBudget.Marked(val);
			if (peer.OwesReply || percent != peer.LastPercent || num != peer.LastMarked)
			{
				((NetworkConnection)c).Send<FreeBudgetState>(new FreeBudgetState
				{
					Percent = (byte)percent,
					Marked = num,
					Reply = peer.OwesReply
				}, 0);
				peer.OwesReply = false;
				peer.LastPercent = percent;
				peer.LastMarked = num;
			}
		}
	}

	private static void Receive(FreeBudgetState state)
	{
		View = state;
		Ready = true;
		if (state.Reply)
		{
			Feedback = ((!PendingRelease) ? ((PendingRate == state.Percent) ? "Rate saved." : "Rate was not applied. Try again after loading.") : ((state.Marked == 0) ? "Holdings released." : "Release failed. Try again after loading."));
			PendingRate = -1;
			PendingRelease = false;
		}
	}

	internal static void Submit(int percent)
	{
		if (Ready && !Waiting && NetworkClient.ready && percent >= 0 && percent <= 100)
		{
			PendingRate = percent;
			Feedback = "";
			NetworkClient.Send<FreeBudgetRate>(new FreeBudgetRate
			{
				Percent = (byte)percent
			}, 0);
		}
	}

	internal static void SubmitRelease()
	{
		if (Ready && !Waiting && NetworkClient.ready)
		{
			PendingRelease = true;
			Feedback = "";
			NetworkClient.Send<FreeBudgetRelease>(default(FreeBudgetRelease), 0);
		}
	}
}
[HarmonyPatch(typeof(FinanceManager), "UserCode_CmdRequestAccount__UInt64__String__NetworkConnectionToClient")]
internal static class FreeBudgetProbe
{
	private static bool Prefix(ulong steamId, string displayName, NetworkConnectionToClient sender)
	{
		if (!GameMode.IsIncremental || steamId != ulong.MaxValue || displayName != "SeparateWallets/free-budget/2?")
		{
			return true;
		}
		FreeBudgetNet.Join(sender);
		return false;
	}
}
[Serializable]
public sealed class WalletWorldSaveData : IncrementalWorldSaveData
{
	public FreeBudgetAllowance[] separateWalletsFreeBudget;
}
[HarmonyPatch(typeof(SaveManager), "CollectWorld")]
internal static class SaveFreeBudget
{
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		ConstructorInfo original = typeof(IncrementalWorldSaveData).GetConstructor(Type.EmptyTypes);
		ConstructorInfo extended = typeof(WalletWorldSaveData).GetConstructor(Type.EmptyTypes);
		int matches = 0;
		foreach (CodeInstruction instruction in instructions)
		{
			if (instruction.opcode == OpCodes.Newobj && object.Equals(instruction.operand, original))
			{
				instruction.operand = extended;
				matches++;
			}
			yield return instruction;
		}
		if (matches != 1)
		{
			throw new InvalidOperationException("Could not locate Incremental world snapshot construction.");
		}
	}

	private static void Postfix(WorldSaveData __result)
	{
		if (__result is WalletWorldSaveData walletWorldSaveData)
		{
			walletWorldSaveData.separateWalletsFreeBudget = FreeBudget.Capture(((WorldSaveData)walletWorldSaveData).finance);
		}
	}
}
[HarmonyPatch(typeof(SaveManager), "ParseWorld")]
internal static class LoadFreeBudget
{
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		return Calls.Replace(instructions, new Func<string, IncrementalWorldSaveData>(JsonUtility.FromJson<IncrementalWorldSaveData>).Method, AccessTools.Method(typeof(LoadFreeBudget), "Read", (Type[])null, (Type[])null));
	}

	internal static IncrementalWorldSaveData Read(string json)
	{
		WalletWorldSaveData walletWorldSaveData = JsonUtility.FromJson<WalletWorldSaveData>(json);
		if (walletWorldSaveData != null)
		{
			FreeBudget.Restore(((WorldSaveData)walletWorldSaveData).finance, walletWorldSaveData.separateWalletsFreeBudget);
		}
		return (IncrementalWorldSaveData)(object)walletWorldSaveData;
	}
}
internal sealed class Funding
{
	internal static Funding Active;

	private static uint serial;

	internal readonly uint Id = ++serial;

	internal uint Revision = 1u;

	internal readonly double Deadline = NetworkTime.time + 120.0;

	internal readonly NetworkConnectionToClient Buyer;

	internal readonly ulong BuyerId;

	internal readonly string BuyerName;

	internal readonly string Item;

	internal readonly string Reason;

	internal readonly int Price;

	internal readonly int Own;

	private readonly FinanceManager finance;

	private readonly PlayerAccount buyerAccount;

	private readonly Purchase purchase;

	internal readonly Dictionary<ulong, int> Pledges = new Dictionary<ulong, int>();

	private readonly List<(PlayerAccount Account, BudgetMove Move)> moved = new List<(PlayerAccount, BudgetMove)>();

	private static ulong lastFreeExtra;

	private ulong nextFreeExtra;

	private bool automatic;

	private bool settling;

	private bool paid;

	private bool chargeEntered;

	internal int Gap => Price - Own;

	internal int Remaining { get; private set; }

	private Funding(Purchase attempt, NetworkConnectionToClient c, PlayerController p, int price, string reason)
	{
		finance = FinanceManager.instance;
		buyerAccount = finance.GetAccount(p.steamId);
		Buyer = c;
		BuyerId = p.steamId;
		BuyerName = Wallets.Display(p);
		Own = buyerAccount?.balance ?? 0;
		Price = price;
		Remaining = Gap;
		Reason = reason;
		purchase = attempt;
		string[] array = reason.Split('\u001f');
		string text = ((array.Length > 1) ? array[1] : reason);
		Item = (text.StartsWith("@") ? LocalizationManager.Get(text.Substring(1), Array.Empty<object>()) : text) + ((array.Length > 2) ? (" (" + array[2] + ")") : "");
	}

	internal static bool BeforeCharge(NetworkConnectionToClient c, PlayerController p, int price, int seen, string reason)
	{
		Funding active = Active;
		if (active != null && active.settling)
		{
			if (active.chargeEntered || c != active.Buyer || price != active.Price || seen != price || reason != active.Reason || !active.purchase.Matches(Purchase.Current) || !active.Valid())
			{
				return false;
			}
			active.chargeEntered = true;
			return active.FundBuyer();
		}
		if (!GameMode.IsIncremental || !NetworkServer.active || Purchase.Current == null || price != seen || price <= 0 || !FundingNet.Supports(c) || !Wallets.Eligible(c, out var player) || (Object)(object)p != (Object)(object)player || !p.balanceKnown || SaveManager.LoadInProgress || IncrementalEggSwap.ServerSwapping || (Object)(object)FinanceManager.instance == (Object)null)
		{
			return true;
		}
		Tick();
		if (Active != null && Active.Buyer == c && Active.purchase.Matches(Purchase.Current))
		{
			FundingNet.Push(c, "This purchase already has a funding request. Cancel it to buy separately.");
			return false;
		}
		int num = FinanceManager.instance.GetAccount(p.steamId)?.balance ?? 0;
		if ((long)price <= (long)(num - Held(p.steamId)))
		{
			return true;
		}
		if (Active != null)
		{
			FundingNet.Push(c, "Another funding request is already open.");
		}
		else
		{
			int num2 = UnfundableCents(p.steamId, price - num);
			if (num2 > 0)
			{
				FundingNet.Push(c, "The crew needs another " + Money.ExactGrouped(num2) + " to afford this purchase.");
				return false;
			}
			Funding funding = (Active = new Funding(Purchase.Current, c, p, price, reason));
			funding.automatic = FreeBudget.TryPlan(funding.finance, funding.BuyerId, funding.Gap, funding.Pledges, lastFreeExtra, out funding.nextFreeExtra);
			if (funding.automatic)
			{
				funding.Remaining = 0;
				funding.Complete();
			}
			else
			{
				FundingNet.Broadcast();
			}
		}
		return false;
	}

	private static int UnfundableCents(ulong buyer, int gap)
	{
		HashSet<ulong> hashSet = new HashSet<ulong> { buyer };
		foreach (NetworkConnectionToClient value2 in NetworkServer.connections.Values)
		{
			if (Wallets.Eligible(value2, out var player) && FundingNet.Participants.TryGetValue(value2, out var value) && value == player.steamId && hashSet.Add(value))
			{
				int num = FinanceManager.instance.GetAccount(value)?.balance ?? 0;
				if (num >= gap)
				{
					return 0;
				}
				gap -= Math.Max(0, num);
			}
		}
		return gap;
	}

	internal static int Held(ulong id)
	{
		Funding active = Active;
		if (active == null || active.settling)
		{
			return 0;
		}
		if (id != active.BuyerId)
		{
			if (!active.Pledges.TryGetValue(id, out var value))
			{
				return 0;
			}
			return value;
		}
		return active.Own;
	}

	private bool Valid()
	{
		if (NetworkServer.active && GameMode.IsIncremental && !SaveManager.LoadInProgress && !IncrementalEggSwap.ServerSwapping && NetworkTime.time < Deadline && (Object)(object)finance != (Object)null && (Object)(object)finance == (Object)(object)FinanceManager.instance && (Object)(object)purchase.Shop != (Object)null && (Object)(object)purchase.Shop == (Object)(object)IncrementalTools.Instance && buyerAccount == finance.GetAccount(BuyerId) && Wallets.Eligible(Buyer, out var player))
		{
			return player.steamId == BuyerId;
		}
		return false;
	}

	internal static void Tick()
	{
		Funding active = Active;
		if (active != null && !active.settling && !active.Valid())
		{
			active.End((NetworkTime.time >= active.Deadline) ? "Funding request expired." : "Purchase canceled because the buyer or shop is unavailable.");
		}
	}

	internal static void Leave(NetworkConnectionToClient c)
	{
		Funding active = Active;
		if (active != null && !active.settling)
		{
			ulong value;
			if (c == active.Buyer)
			{
				active.End("Funding request canceled. The buyer left.");
			}
			else if (FundingNet.Participants.TryGetValue(c, out value))
			{
				active.Withdraw(value);
			}
		}
	}

	private void Withdraw(ulong id)
	{
		if (Pledges.TryGetValue(id, out var value))
		{
			Pledges.Remove(id);
			Remaining += value;
			Revision++;
			FundingNet.Broadcast();
		}
	}

	internal static void Respond(NetworkConnectionToClient c, FundingVote m)
	{
		Tick();
		Funding active = Active;
		if (!FundingNet.Supports(c) || !Wallets.Eligible(c, out var player) || FundingNet.Participants[c] != player.steamId)
		{
			return;
		}
		if (active == null || m.Id != active.Id || active.settling)
		{
			FundingNet.Push(c);
		}
		else if (m.Action == 3 && c == active.Buyer)
		{
			active.End("Funding request canceled by the buyer.");
		}
		else
		{
			if (c == active.Buyer)
			{
				return;
			}
			if (m.Action == 2)
			{
				active.Withdraw(player.steamId);
				FundingNet.Push(c);
				return;
			}
			if (m.Action != 1 || m.Revision != active.Revision || active.Pledges.ContainsKey(player.steamId) || m.Cents <= 0 || m.Cents > active.Remaining || m.Cents > (active.finance.GetAccount(player.steamId)?.balance ?? 0))
			{
				FundingNet.Push(c, "Review the current balance and choose your contribution again.");
				return;
			}
			active.Pledges.Add(player.steamId, m.Cents);
			active.Remaining -= m.Cents;
			active.Revision++;
			if (active.Remaining == 0)
			{
				active.Complete();
			}
			else
			{
				FundingNet.Broadcast();
			}
		}
	}

	private bool CanPay(ulong id, int cents)
	{
		PlayerAccount account = finance.GetAccount(id);
		if (account != null && account.balance >= cents && FundingNet.Online(id))
		{
			if (automatic)
			{
				return FreeBudget.Marked(account) >= cents;
			}
			return true;
		}
		return false;
	}

	private bool FundBuyer()
	{
		int num = finance.GetAccount(BuyerId)?.balance ?? 0;
		if (num < Own || (long)num + (long)Gap > int.MaxValue)
		{
			return false;
		}
		foreach (KeyValuePair<ulong, int> pledge in Pledges)
		{
			if (!CanPay(pledge.Key, pledge.Value))
			{
				return false;
			}
		}
		foreach (KeyValuePair<ulong, int> pledge2 in Pledges)
		{
			if (moved.Count > 0 && !CanPay(pledge2.Key, pledge2.Value))
			{
				return false;
			}
			PlayerAccount account = finance.GetAccount(pledge2.Key);
			BudgetMove budgetMove = new BudgetMove
			{
				MarkedFirst = automatic
			};
			moved.Add((account, budgetMove));
			if (Wallets.Move(finance, pledge2.Key, BuyerId, pledge2.Value, account.displayName, BuyerName, budgetMove) != pledge2.Value || budgetMove.Sent != pledge2.Value || budgetMove.Received != pledge2.Value || (automatic && budgetMove.MarkedSpent != pledge2.Value))
			{
				return false;
			}
		}
		return true;
	}

	internal static void Charged(bool success)
	{
		if (success && Active != null && Active.settling && Active.chargeEntered)
		{
			Active.paid = true;
		}
	}

	private void Complete()
	{
		settling = true;
		try
		{
			purchase.Replay();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Funded shop purchase: " + ex));
		}
		finally
		{
			try
			{
				if (!paid)
				{
					for (int num = moved.Count - 1; num >= 0; num--)
					{
						var (val, budgetMove) = moved[num];
						if (budgetMove.Received > 0)
						{
							BudgetMove receipt = new BudgetMove
							{
								RestoreOnReceipt = budgetMove.MarkedSpent
							};
							try
							{
								Wallets.Move(finance, BuyerId, val.steamId, budgetMove.Received, BuyerName, val.displayName, receipt);
							}
							catch (Exception ex2)
							{
								Plugin.Log.LogError((object)("Crew payment refund: " + ex2));
							}
						}
					}
				}
			}
			finally
			{
				if (paid && automatic)
				{
					lastFreeExtra = nextFreeExtra;
				}
				string text = (automatic ? (BuyerName + " used " + Money.ExactGrouped(Gap) + " of crew Free Budget to buy " + Item + ".") : (BuyerName + " purchased " + Item + " with crew funding."));
				End(paid ? text : "Purchase canceled. Check the current price, stock and balances.");
			}
		}
	}

	private void End(string message)
	{
		Active = null;
		FundingNet.Broadcast(message);
	}
}
[HarmonyPatch]
internal sealed class Purchase
{
	[ThreadStatic]
	internal static Purchase Current;

	internal readonly IncrementalTools Shop;

	private readonly MethodInfo method;

	private readonly object[] args;

	private Purchase(IncrementalTools shop, MethodBase target, object[] args)
	{
		Shop = shop;
		method = (MethodInfo)target;
		this.args = (object[])args.Clone();
	}

	internal void Replay()
	{
		method.Invoke(Shop, args);
	}

	internal bool Matches(Purchase other)
	{
		if (other != null && (Object)(object)Shop == (Object)(object)other.Shop && method == other.method && object.Equals(args[0], other.args[0]))
		{
			return object.Equals(args[1], other.args[1]);
		}
		return false;
	}

	private static IEnumerable<MethodBase> TargetMethods()
	{
		string[] array = new string[5] { "OnBuy", "OnBuyUpgrade", "OnBuyLift", "OnBuyCollector", "OnBuyDepot" };
		foreach (string text in array)
		{
			yield return AccessTools.Method(typeof(IncrementalTools), text, (Type[])null, (Type[])null);
		}
	}

	private static void Prefix(IncrementalTools __instance, MethodBase __originalMethod, object[] __args, out Purchase __state)
	{
		__state = Current;
		Current = new Purchase(__instance, __originalMethod, __args);
	}

	private static void Finalizer(Purchase __state)
	{
		Current = __state;
	}
}
[HarmonyPatch(typeof(IncrementalTools), "ServerCharge")]
internal static class FundingCharge
{
	private static bool Prefix(NetworkConnectionToClient conn, PlayerController controller, int cents, int seenCents, string reason)
	{
		return Funding.BeforeCharge(conn, controller, cents, seenCents, reason);
	}

	private static void Postfix(bool __result)
	{
		Funding.Charged(__result);
	}
}
[HarmonyPatch(typeof(FinanceManager), "Debit")]
internal static class BudgetDebit
{
	private static bool Prefix(FinanceManager __instance, ulong steamId, int amount)
	{
		int num = Funding.Held(steamId);
		if (num != 0)
		{
			return amount <= (__instance.GetAccount(steamId)?.balance ?? 0) - num;
		}
		return true;
	}
}
[HarmonyPatch(typeof(FinanceManager), "ServerTransfer")]
internal static class BudgetTransfer
{
	private static bool Prefix(FinanceManager __instance, ulong fromSteamId, int cents)
	{
		int num = Funding.Held(fromSteamId);
		if (num != 0)
		{
			return cents <= (__instance.GetAccount(fromSteamId)?.balance ?? 0) - num;
		}
		return true;
	}
}
internal struct FundingVote : NetworkMessage
{
	internal const byte Confirm = 1;

	internal const byte Withdraw = 2;

	internal const byte Cancel = 3;

	internal uint Id;

	internal uint Revision;

	internal int Cents;

	internal byte Action;
}
internal struct FundingState : NetworkMessage
{
	internal uint Id;

	internal uint Revision;

	internal int Price;

	internal int Gap;

	internal int Left;

	internal int Mine;

	internal bool Buyer;

	internal double Deadline;

	internal string Name;

	internal string Item;

	internal string Notice;
}
internal static class FundingNet
{
	internal const string Probe = "SeparateWallets/funding/1?";

	internal static readonly Dictionary<NetworkConnectionToClient, ulong> Participants = new Dictionary<NetworkConnectionToClient, ulong>();

	internal static FundingState View;

	internal static bool Ready;

	internal static int Draft;

	internal static string Feedback = "";

	private static int probes;

	private static float nextProbe;

	internal static void Codecs()
	{
		Writer<FundingVote>.write = delegate(NetworkWriter w, FundingVote m)
		{
			NetworkWriterExtensions.WriteUInt(w, m.Id);
			NetworkWriterExtensions.WriteUInt(w, m.Revision);
			NetworkWriterExtensions.WriteInt(w, m.Cents);
			w.WriteByte(m.Action);
		};
		Reader<FundingVote>.read = (NetworkReader r) => new FundingVote
		{
			Id = NetworkReaderExtensions.ReadUInt(r),
			Revision = NetworkReaderExtensions.ReadUInt(r),
			Cents = NetworkReaderExtensions.ReadInt(r),
			Action = r.ReadByte()
		};
		Writer<FundingState>.write = delegate(NetworkWriter w, FundingState m)
		{
			NetworkWriterExtensions.WriteUInt(w, m.Id);
			NetworkWriterExtensions.WriteUInt(w, m.Revision);
			NetworkWriterExtensions.WriteInt(w, m.Price);
			NetworkWriterExtensions.WriteInt(w, m.Gap);
			NetworkWriterExtensions.WriteInt(w, m.Left);
			NetworkWriterExtensions.WriteInt(w, m.Mine);
			NetworkWriterExtensions.WriteBool(w, m.Buyer);
			NetworkWriterExtensions.WriteDouble(w, m.Deadline);
			NetworkWriterExtensions.WriteString(w, m.Name);
			NetworkWriterExtensions.WriteString(w, m.Item);
			NetworkWriterExtensions.WriteString(w, m.Notice);
		};
		Reader<FundingState>.read = (NetworkReader r) => new FundingState
		{
			Id = NetworkReaderExtensions.ReadUInt(r),
			Revision = NetworkReaderExtensions.ReadUInt(r),
			Price = NetworkReaderExtensions.ReadInt(r),
			Gap = NetworkReaderExtensions.ReadInt(r),
			Left = NetworkReaderExtensions.ReadInt(r),
			Mine = NetworkReaderExtensions.ReadInt(r),
			Buyer = NetworkReaderExtensions.ReadBool(r),
			Deadline = NetworkReaderExtensions.ReadDouble(r),
			Name = NetworkReaderExtensions.ReadString(r),
			Item = NetworkReaderExtensions.ReadString(r),
			Notice = NetworkReaderExtensions.ReadString(r)
		};
	}

	internal static void StartServer()
	{
		StopServer();
		NetworkServer.ReplaceHandler<FundingVote>((Action<NetworkConnectionToClient, FundingVote>)Funding.Respond, true);
	}

	internal static void StopServer()
	{
		Participants.Clear();
		Funding.Active = null;
	}

	internal static void StartClient()
	{
		ResetClient();
		NetworkClient.ReplaceHandler<FundingState>((Action<FundingState>)Receive, true);
	}

	internal static void ResetClient()
	{
		View = default(FundingState);
		Draft = 0;
		Ready = false;
		probes = 0;
		nextProbe = 0f;
		Feedback = "";
	}

	internal static bool Supports(NetworkConnectionToClient c)
	{
		if (c != null)
		{
			return Participants.ContainsKey(c);
		}
		return false;
	}

	internal static bool Online(ulong id)
	{
		foreach (KeyValuePair<NetworkConnectionToClient, ulong> participant in Participants)
		{
			if (participant.Value == id && Wallets.Eligible(participant.Key, out var player) && player.steamId == id)
			{
				return true;
			}
		}
		return false;
	}

	internal static void TickClient()
	{
		if (!Ready && probes < 5 && !(Time.unscaledTime < nextProbe) && NetworkClient.ready && !((Object)(object)NetworkClient.localPlayer == (Object)null) && !((Object)(object)FinanceManager.instance == (Object)null) && ((NetworkBehaviour)FinanceManager.instance).netId != 0 && NetworkClient.spawned.ContainsKey(((NetworkBehaviour)FinanceManager.instance).netId))
		{
			PlayerController component = ((Component)NetworkClient.localPlayer).GetComponent<PlayerController>();
			if (!((Object)(object)component == (Object)null) && component.balanceKnown)
			{
				probes++;
				nextProbe = Time.unscaledTime + 3f;
				FinanceManager.instance.CmdRequestAccount(ulong.MaxValue, "SeparateWallets/funding/1?", (NetworkConnectionToClient)null);
			}
		}
	}

	internal static void Join(NetworkConnectionToClient conn)
	{
		ulong num = default(ulong);
		if (Wallets.Eligible(conn, out var player) && (!MyNetworkManager.TryGetSteamId(conn, ref num) || num == player.steamId))
		{
			Participants[conn] = player.steamId;
			Push(conn);
		}
	}

	internal static void Leave(NetworkConnectionToClient conn)
	{
		Funding.Leave(conn);
		Participants.Remove(conn);
	}

	internal static void Broadcast(string notice = "")
	{
		foreach (NetworkConnectionToClient item in new List<NetworkConnectionToClient>(Participants.Keys))
		{
			Push(item, notice);
		}
	}

	internal static void Push(NetworkConnectionToClient c, string notice = "")
	{
		if (Participants.TryGetValue(c, out var value) && ((NetworkConnection)c).isReady)
		{
			Funding active = Funding.Active;
			FundingState fundingState = new FundingState
			{
				Notice = notice
			};
			if (active != null)
			{
				fundingState.Id = active.Id;
				fundingState.Revision = active.Revision;
				fundingState.Price = active.Price;
				fundingState.Gap = active.Gap;
				fundingState.Left = active.Remaining;
				active.Pledges.TryGetValue(value, out fundingState.Mine);
				fundingState.Deadline = active.Deadline;
				fundingState.Buyer = c == active.Buyer;
				fundingState.Name = active.BuyerName;
				fundingState.Item = active.Item;
			}
			((NetworkConnection)c).Send<FundingState>(fundingState, 0);
		}
	}

	internal static void Receive(FundingState s)
	{
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		bool num = s.Id != View.Id || s.Revision != View.Revision;
		bool flag = s.Id != 0 && s.Id != View.Id;
		if (num || !string.IsNullOrEmpty(s.Notice))
		{
			Draft = 0;
		}
		if (num)
		{
			Feedback = "";
		}
		Ready = true;
		View = s;
		if (flag)
		{
			Announce(s.Name + " needs " + Money.ExactGrouped(s.Gap) + " for " + s.Item + ". Press " + ((object)Plugin.BudgetKey.Value/*cast due to .constrained prefix*/).ToString() + " and choose Crew funding to contribute.");
		}
		if (!string.IsNullOrEmpty(s.Notice))
		{
			Announce(s.Notice);
		}
	}

	private static void Announce(string line)
	{
		Feedback = line;
		if (Chainloader.PluginInfos.TryGetValue("crack.textchat", out var value) && (Object)(object)value.Instance != (Object)null)
		{
			Type type = AccessTools.TypeByName("CrackTextChat.ChatView");
			Component val = ((type == null) ? null : ((Component)value.Instance).GetComponent(type));
			if ((Object)(object)val != (Object)null)
			{
				AccessTools.Method(((object)val).GetType(), "Add", (Type[])null, (Type[])null).Invoke(val, new object[3] { "Crew funding", line, true });
			}
		}
	}

	internal static void Submit(byte action, int cents = 0)
	{
		if (Ready && View.Id != 0 && NetworkClient.ready)
		{
			NetworkClient.Send<FundingVote>(new FundingVote
			{
				Id = View.Id,
				Revision = View.Revision,
				Action = action,
				Cents = cents
			}, 0);
		}
	}
}
[HarmonyPatch(typeof(FinanceManager), "UserCode_CmdRequestAccount__UInt64__String__NetworkConnectionToClient")]
internal static class FundingProbe
{
	private static bool Prefix(ulong steamId, string displayName, NetworkConnectionToClient sender)
	{
		if (!GameMode.IsIncremental || steamId != ulong.MaxValue || displayName != "SeparateWallets/funding/1?")
		{
			return true;
		}
		FundingNet.Join(sender);
		return false;
	}
}
internal static class MoneyRules
{
	internal static int Divide(int cents, IReadOnlyList<int> balances, int start, int[] shares, out int lastExtra)
	{
		int[] array = new int[balances.Count];
		for (int i = 0; i < array.Length; i++)
		{
			array[i] = int.MaxValue - balances[i];
		}
		return DivideByCapacity(cents, array, start, shares, out lastExtra);
	}

	internal static int DivideByCapacity(int cents, IReadOnlyList<int> limits, int start, int[] shares, out int lastExtra)
	{
		lastExtra = -1;
		List<int> list = new List<int>(limits.Count);
		for (int i = 0; i < limits.Count; i++)
		{
			int num = (start + i) % limits.Count;
			if (limits[num] > 0)
			{
				list.Add(num);
			}
		}
		int num2 = cents;
		while (num2 > 0 && list.Count > 0)
		{
			int num3 = num2 / list.Count;
			bool flag = false;
			for (int num4 = list.Count - 1; num4 >= 0; num4--)
			{
				int num5 = list[num4];
				int num6 = limits[num5];
				if (num6 <= num3)
				{
					shares[num5] = num6;
					num2 -= shares[num5];
					list.RemoveAt(num4);
					flag = true;
				}
			}
			if (flag)
			{
				continue;
			}
			int num7 = num2 % list.Count;
			for (int j = 0; j < list.Count; j++)
			{
				int num8 = list[j];
				shares[num8] = num3 + ((j < num7) ? 1 : 0);
				if (j < num7)
				{
					lastExtra = num8;
				}
			}
			num2 = 0;
		}
		return num2;
	}

	internal static bool TryReadAmount(string text, out int cents)
	{
		cents = 0;
		string text2 = (text ?? "").Trim().Replace(',', '.');
		if (text2.Length == 0 || text2.Length > 16)
		{
			return false;
		}
		int num = text2.IndexOf('.');
		if (num >= 0 && (text2.Length - num - 1 > 2 || text2.LastIndexOf('.') != num))
		{
			return false;
		}
		string text3 = text2;
		foreach (char c in text3)
		{
			if ((c < '0' || c > '9') && c != '.')
			{
				return false;
			}
		}
		if (!decimal.TryParse(text2, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var result) || result <= 0m || result > 21474836.47m)
		{
			return false;
		}
		cents = (int)(result * 100m);
		return cents > 0;
	}
}
internal static class OfflineWallets
{
	internal sealed class Offer
	{
		internal readonly PlayerAccount Account;

		internal readonly int Cents;

		internal ulong Id => Account.steamId;

		internal string Name
		{
			get
			{
				if (!string.IsNullOrWhiteSpace(Account.displayName))
				{
					return Account.displayName;
				}
				return "Player";
			}
		}

		internal Offer(PlayerAccount account)
		{
			Account = account;
			Cents = account.balance;
		}
	}

	internal static bool IsLocalHost
	{
		get
		{
			if (NetworkServer.active && NetworkServer.localConnection != null && (Object)(object)NetworkClient.localPlayer != (Object)null)
			{
				return (Object)(object)((NetworkConnection)NetworkServer.localConnection).identity == (Object)(object)NetworkClient.localPlayer;
			}
			return false;
		}
	}

	private static string ReadRoster(HashSet<ulong> connected, out PlayerController host)
	{
		host = null;
		if (!GameMode.IsIncremental || !IsLocalHost || !Wallets.Eligible((NetworkConnectionToClient)(object)NetworkServer.localConnection, out host))
		{
			return "Only the session host can claim an offline wallet.";
		}
		if (SaveManager.LoadInProgress || IncrementalEggSwap.ServerSwapping || (Object)(object)FinanceManager.instance == (Object)null || !host.balanceKnown)
		{
			return "Wallets are loading. Try again in a moment.";
		}
		connected.Add(host.steamId);
		ulong num = default(ulong);
		foreach (NetworkConnectionToClient value in NetworkServer.connections.Values)
		{
			if (value != null)
			{
				PlayerController val = (((Object)(object)((NetworkConnection)value).identity != (Object)null) ? ((Component)((NetworkConnection)value).identity).GetComponent<PlayerController>() : null);
				bool flag = (Object)(object)val != (Object)null && Wallets.PersonalId(val.steamId);
				if (flag)
				{
					connected.Add(val.steamId);
				}
				if (MyNetworkManager.TryGetSteamId(value, ref num) && Wallets.PersonalId(num))
				{
					connected.Add(num);
				}
				else if (!flag)
				{
					return "A player is joining. Check again when they finish connecting.";
				}
			}
		}
		return "";
	}

	internal static string List(List<Offer> offers)
	{
		offers.Clear();
		HashSet<ulong> hashSet = new HashSet<ulong>();
		PlayerController host;
		string text = ReadRoster(hashSet, out host);
		if (text.Length != 0)
		{
			return text;
		}
		foreach (PlayerAccount account in FinanceManager.instance.GetSaveData().accounts)
		{
			if (account != null && Wallets.PersonalId(account.steamId) && account.balance > 0 && !hashSet.Contains(account.steamId))
			{
				offers.Add(new Offer(account));
			}
		}
		offers.Sort((Offer a, Offer b) => a.Id.CompareTo(b.Id));
		return "";
	}

	internal static string Claim(Offer offer)
	{
		HashSet<ulong> hashSet = new HashSet<ulong>();
		PlayerController host;
		string text = ReadRoster(hashSet, out host);
		if (text.Length != 0)
		{
			return text;
		}
		if (offer == null || !Wallets.PersonalId(offer.Id) || hashSet.Contains(offer.Id))
		{
			return "This wallet is no longer available to claim.";
		}
		FinanceManager instance = FinanceManager.instance;
		PlayerAccount account = instance.GetAccount(offer.Id);
		if (account != offer.Account || offer.Cents <= 0 || account.balance != offer.Cents)
		{
			return "The wallet changed. Select it again to review the new balance.";
		}
		PlayerAccount account2 = instance.GetAccount(host.steamId);
		if (account2 == null)
		{
			return "Your wallet is still loading.";
		}
		if ((long)account2.balance + (long)offer.Cents > int.MaxValue)
		{
			return "Your wallet has too little room for the full balance.";
		}
		int num = Wallets.Move(instance, offer.Id, host.steamId, offer.Cents, offer.Account.displayName, Wallets.Display(host));
		if (num != offer.Cents)
		{
			return "Check both balances before trying again.";
		}
		return "Claimed " + Money.ExactGrouped(num) + " from " + offer.Name + ".";
	}
}
[BepInPlugin("crack.incremental.separatewallets", "Separate Wallets", "0.4.2")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	internal const string Id = "crack.incremental.separatewallets";

	internal static ManualLogSource Log;

	internal static ConfigEntry<Key> BudgetKey;

	private Harmony patches;

	private float nextSettlement;

	internal static bool Installed { get; private set; }

	private void Awake()
	{
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Expected O, but got Unknown
		//IL_007b: 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)
		Log = ((BaseUnityPlugin)this).Logger;
		BudgetKey = ((BaseUnityPlugin)this).Config.Bind<Key>("Controls", "FundingMenuKey", (Key)101, "Keyboard key that opens or closes the Wallet menu.");
		patches = new Harmony("crack.incremental.separatewallets");
		try
		{
			Wire.InstallCodecs();
			FundingNet.Codecs();
			FreeBudgetNet.Codecs();
			patches.PatchAll(typeof(Plugin).Assembly);
			Installed = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Separate Wallets loaded. Wallet key: " + ((object)BudgetKey.Value/*cast due to .constrained prefix*/).ToString()));
		}
		catch (Exception ex)
		{
			patches.UnpatchSelf();
			((BaseUnityPlugin)this).Logger.LogError((object)("Wallet integration could not load for this build of CRACK. " + ex));
		}
	}

	private void Update()
	{
		//IL_0034: 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)
		if (!Installed)
		{
			return;
		}
		if (NetworkServer.active)
		{
			Funding.Tick();
		}
		if (GameMode.IsIncremental)
		{
			FundingNet.TickClient();
			FreeBudgetNet.TickClient();
			Keyboard current = Keyboard.current;
			if (current != null && (int)BudgetKey.Value != 0 && ((ButtonControl)current[BudgetKey.Value]).wasPressedThisFrame)
			{
				WalletMenu.ToggleWallet();
			}
			Wire.UpdateClient();
			if (NetworkServer.active && !SaveManager.LoadInProgress && !(Time.unscaledTime < nextSettlement))
			{
				nextSettlement = Time.unscaledTime + 0.5f;
				Wallets.SettleReserve(FinanceManager.instance);
				FreeBudgetNet.Sync();
			}
		}
	}

	private void OnDestroy()
	{
		Installed = false;
		Wire.Shutdown();
		Harmony obj = patches;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
	}
}
[HarmonyPatch(typeof(GameMenu), "Open")]
internal static class OpenPauseMenu
{
	private static void Postfix(GameMenu __instance, CanvasGroup ____mainPanel, ref CanvasGroup[] ____panels)
	{
		if (!GameMode.IsIncremental || !__instance.IsOpen || (Object)(object)____mainPanel == (Object)null)
		{
			return;
		}
		WalletMenu component = ((Component)__instance).GetComponent<WalletMenu>();
		if (!((Object)(object)component == (Object)null))
		{
			return;
		}
		component = ((Component)__instance).gameObject.AddComponent<WalletMenu>();
		try
		{
			CanvasGroup val = component.Build(__instance, ____mainPanel);
			CanvasGroup val2 = component.BuildBudgetPanel();
			Array.Resize(ref ____panels, ____panels.Length + 2);
			____panels[____panels.Length - 2] = val;
			____panels[____panels.Length - 1] = val2;
		}
		catch (Exception ex)
		{
			component.DiscardIncompleteMenu();
			Plugin.Log.LogError((object)("Could not build the Wallet menu. " + ex));
		}
	}
}
[HarmonyPatch(typeof(GameMenu), "Close")]
internal static class CloseWalletMenu
{
	private static void Postfix(GameMenu __instance)
	{
		((Component)__instance).GetComponent<WalletMenu>()?.HideOverlay();
	}
}
public sealed class WalletMenu : MonoBehaviour
{
	private enum WalletTab
	{
		Transfers,
		Offline,
		FreeBudget
	}

	[Serializable]
	[CompilerGenerated]
	private sealed class <>c
	{
		public static readonly <>c <>9 = new <>c();

		public static UnityAction <>9__85_1;

		internal void <BuildBudgetPanel>b__85_1()
		{
			FundingNet.Submit(3);
		}
	}

	private const int PageSize = 4;

	private const float CardWidth = 504f;

	private const float CardHeight = 482f;

	private static readonly Color Ink = Color32.op_Implicit(new Color32((byte)21, (byte)32, (byte)38, byte.MaxValue));

	private static readonly Color Paper = Color32.op_Implicit(new Color32((byte)237, (byte)239, (byte)225, byte.MaxValue));

	private static readonly Color Muted = Color32.op_Implicit(new Color32((byte)172, (byte)187, (byte)180, byte.MaxValue));

	private static readonly Color Surface = Color32.op_Implicit(new Color32((byte)53, (byte)69, (byte)73, byte.MaxValue));

	private static readonly Color Lime = Color32.op_Implicit(new Color32((byte)208, (byte)233, (byte)135, byte.MaxValue));

	private static readonly Color Teal = Color32.op_Implicit(new Color32((byte)75, (byte)117, (byte)107, byte.MaxValue));

	private static readonly MethodInfo Show = AccessTools.Method(typeof(PanelMenu), "Show", (Type[])null, (Type[])null);

	private GameMenu menu;

	private CanvasGroup panel;

	private RectTransform screenRoot;

	private RectTransform card;

	private TMP_FontAsset font;

	private Button back;

	private Button send;

	private Button previous;

	private Button next;

	private TMP_InputField amount;

	private TMP_Text balance;

	private TMP_Text status;

	private TMP_Text pageLabel;

	private TMP_Text empty;

	private readonly Button[] rows = (Button[])(object)new Button[4];

	private readonly TMP_Text[] rowText = (TMP_Text[])(object)new TMP_Text[4];

	private readonly List<PlayerController> others = new List<PlayerController>();

	private PlayerController local;

	private uint selected;

	private uint seenSuccess;

	private int page;

	private float nextRefresh;

	private RectTransform freeBody;

	private Button freeEntry;

	private Button freeApply;

	private Button freeRelease;

	private Slider freeRate;

	private TMP_Text rateValue;

	private TMP_Text markedValue;

	private TMP_Text freeStatus;

	private int draftRate = -1;

	private CanvasGroup budgetPanel;

	private static WalletMenu visibleMenu;

	private RectTransform budgetCard;

	private RectTransform funded;

	private TMP_Text subject;

	private TMP_Text progress;

	private TMP_Text countdown;

	private TMP_Text myBudget;

	private TMP_Text feedback;

	private Slider pledge;

	private Button commit;

	private Button cancelBudget;

	private TMP_Text commitText;

	private Button budgetClose;

	private RectTransform sendBody;

	private RectTransform offlineBody;

	private Button offlineEntry;

	private Button claim;

	private Button older;

	private Button newer;

	private TMP_Text offlinePageLabel;

	private TMP_Text claimStatus;

	private TMP_Text claimOwner;

	private readonly Button[] offlineRows = (Button[])(object)new Button[4];

	private readonly TMP_Text[] offlineNames = (TMP_Text[])(object)new TMP_Text[4];

	private readonly List<OfflineWallets.Offer> offers = new List<OfflineWallets.Offer>();

	private OfflineWallets.Offer selection;

	private int offlinePage;

	private string claimFeedback = "";

	internal static bool IsVisible
	{
		get
		{
			if ((Object)(object)visibleMenu != (Object)null && visibleMenu.menu.IsOpen && (Object)(object)visibleMenu.screenRoot != (Object)null)
			{
				return ((Component)visibleMenu.screenRoot).gameObject.activeInHierarchy;
			}
			return false;
		}
	}

	internal CanvasGroup Build(GameMenu owner, CanvasGroup mainPanel)
	{
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Expected O, but got Unknown
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Expected O, but got Unknown
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: 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_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: 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_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: 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_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		//IL_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0215: Expected O, but got Unknown
		//IL_023f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0276: Unknown result type (might be due to invalid IL or missing references)
		//IL_02af: Unknown result type (might be due to invalid IL or missing references)
		//IL_030a: Unknown result type (might be due to invalid IL or missing references)
		//IL_032e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0347: Unknown result type (might be due to invalid IL or missing references)
		//IL_034c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0356: Expected O, but got Unknown
		//IL_036b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0384: Unknown result type (might be due to invalid IL or missing references)
		//IL_0389: Unknown result type (might be due to invalid IL or missing references)
		//IL_0393: Expected O, but got Unknown
		//IL_03be: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0400: Unknown result type (might be due to invalid IL or missing references)
		//IL_0405: Unknown result type (might be due to invalid IL or missing references)
		//IL_040f: Expected O, but got Unknown
		//IL_043a: Unknown result type (might be due to invalid IL or missing references)
		//IL_048b: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ba: Expected O, but got Unknown
		//IL_0503: Unknown result type (might be due to invalid IL or missing references)
		//IL_0547: Unknown result type (might be due to invalid IL or missing references)
		//IL_057e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0597: Unknown result type (might be due to invalid IL or missing references)
		//IL_059c: Unknown result type (might be due to invalid IL or missing references)
		//IL_05a6: Expected O, but got Unknown
		//IL_05d1: Unknown result type (might be due to invalid IL or missing references)
		menu = owner;
		font = TMP_Settings.defaultFontAsset;
		if ((Object)(object)font == (Object)null)
		{
			TMP_Text componentInChildren = ((Component)mainPanel).GetComponentInChildren<TMP_Text>(true);
			font = ((componentInChildren != null) ? componentInChildren.font : null);
		}
		GameObject val = new GameObject("Separate Wallets UI", new Type[3]
		{
			typeof(RectTransform),
			typeof(Canvas),
			typeof(GraphicRaycaster)
		});
		screenRoot = (RectTransform)val.transform;
		Canvas component = val.GetComponent<Canvas>();
		component.renderMode = (RenderMode)0;
		component.sortingOrder = 32766;
		component.pixelPerfect = true;
		val.SetActive(false);
		RectTransform val2 = Node(screenRoot, "Separate Wallets");
		Stretch(val2);
		panel = ((Component)val2).gameObject.AddComponent<CanvasGroup>();
		((Component)val2).gameObject.SetActive(false);
		Fill(val2, Color32.op_Implicit(new Color32((byte)10, (byte)17, (byte)20, (byte)225)));
		card = Node(val2, "Transfer");
		RectTransform obj = card;
		RectTransform obj2 = card;
		RectTransform obj3 = card;
		Vector2 val3 = default(Vector2);
		((Vector2)(ref val3))..ctor(0.5f, 0.5f);
		obj3.pivot = val3;
		Vector2 anchorMin = (obj2.anchorMax = val3);
		obj.anchorMin = anchorMin;
		card.sizeDelta = new Vector2(504f, 482f);
		Fill(card, Ink);
		Fill(Box(card, "Accent", 0f, 0f, 504f, 4f), Lime);
		MakeText(card, "Wallet", 24f, 17f, 109f, 44f, 34f, Paper, (FontStyles)1, (TextAlignmentOptions)513);
		back = MakeButton(card, "Close", new UnityAction(GoBack), 406f, 23f, 74f, 34f, Surface, Paper);
		MakeText(card, "YOUR BALANCE", 24f, 76f, 170f, 28f, 16f, Muted, (FontStyles)1, (TextAlignmentOptions)513);
		balance = MakeText(card, "", 190f, 68f, 290f, 42f, 28f, Lime, (FontStyles)1, (TextAlignmentOptions)516);
		Fill(Box(card, "Divider", 24f, 117f, 456f, 1f), Surface);
		sendBody = Node(card, "Transfers");
		Stretch(sendBody);
		MakeText(sendBody, "Send to", 24f, 129f, 122f, 32f, 22f, Paper, (FontStyles)1, (TextAlignmentOptions)513);
		MakeButton(sendBody, "Crew funding", new UnityAction(OpenFunding), 150f, 129f, 166f, 32f, Surface, Paper);
		previous = MakeButton(sendBody, "‹", (UnityAction)delegate
		{
			ChangePage(-1);
		}, 331f, 129f, 34f, 30f, Surface, Paper);
		pageLabel = MakeText(sendBody, "", 366f, 129f, 77f, 30f, 14f, Muted, (FontStyles)0, (TextAlignmentOptions)514);
		next = MakeButton(sendBody, "›", (UnityAction)delegate
		{
			ChangePage(1);
		}, 446f, 129f, 34f, 30f, Surface, Paper);
		empty = MakeText(sendBody, "No other players are connected.", 24f, 168f, 456f, 48f, 18f, Muted, (FontStyles)0, (TextAlignmentOptions)513);
		for (int num = 0; num < rows.Length; num++)
		{
			int row = num;
			rows[num] = MakeButton(sendBody, "Player", (UnityAction)delegate
			{
				Select(row);
			}, 24f, 168 + 38 * num, 456f, 34f, Surface, Paper);
			rowText[num] = ((Component)rows[num]).GetComponentInChildren<TMP_Text>(true);
			rowText[num].alignment = (TextAlignmentOptions)513;
			rowText[num].margin = new Vector4(12f, 0f, 12f, 0f);
		}
		MakeText(sendBody, "Amount", 24f, 330f, 360f, 28f, 18f, Muted, (FontStyles)1, (TextAlignmentOptions)513);
		amount = MakeAmount(sendBody);
		send = MakeButton(sendBody, "Send money", new UnityAction(Send), 323f, 363f, 157f, 48f, Lime, Ink);
		status = MakeText(sendBody, "", 24f, 422f, 456f, 45f, 16f, Muted, (FontStyles)0, (TextAlignmentOptions)513);
		status.textWrappingMode = (TextWrappingModes)1;
		((UnityEvent<string>)(object)amount.onValueChanged).AddListener((UnityAction<string>)delegate
		{
			Wire.ClearFeedback();
			Refresh();
		});
		BuildOfflineMenu();
		BuildFreeBudgetMenu();
		return panel;
	}

	internal void HideOverlay()
	{
		if ((Object)(object)screenRoot != (Object)null)
		{
			((Component)screenRoot).gameObject.SetActive(false);
		}
	}

	private void OnDestroy()
	{
		if ((Object)(object)screenRoot != (Object)null)
		{
			Object.Destroy((Object)(object)((Component)screenRoot).gameObject);
		}
	}

	internal void DiscardIncompleteMenu()
	{
		((Behaviour)this).enabled = false;
		HideOverlay();
		Object.Destroy((Object)(object)this);
	}

	private void OpenWallet()
	{
		((Component)screenRoot).gameObject.SetActive(true);
		visibleMenu = this;
		Cursor.visible = !ActiveInput.UsingGamepad;
		Show.Invoke(menu, new object[1] { panel });
		ShowWalletTab(WalletTab.Transfers);
		Fit(card);
		Refresh();
		if ((Object)(object)EventSystem.current != (Object)null)
		{
			EventSystem.current.SetSelectedGameObject((others.Count > 0) ? ((Component)rows[0]).gameObject : ((Component)back).gameObject);
		}
	}

	private void Update()
	{
		if ((Object)(object)menu == (Object)null || (Object)(object)screenRoot == (Object)null || !((Component)screenRoot).gameObject.activeSelf)
		{
			return;
		}
		if (menu.IsOpen && (Object)(object)budgetPanel != (Object)null && ((Behaviour)budgetPanel).isActiveAndEnabled && budgetPanel.interactable)
		{
			RenderBudget();
		}
		else if (GameMode.IsIncremental && menu.IsOpen && ((Behaviour)panel).isActiveAndEnabled && panel.interactable)
		{
			Fit(card);
			if (Time.unscaledTime >= nextRefresh)
			{
				nextRefresh = Time.unscaledTime + 0.2f;
				Refresh();
			}
		}
	}

	private void Fit(RectTransform window)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
		Rect rect = screenRoot.rect;
		float num = Mathf.Min((((Rect)(ref rect)).width - 24f) / 504f, (((Rect)(ref rect)).height - 24f) / 482f);
		float num2 = Mathf.Max(1, Mathf.RoundToInt(((Rect)(ref rect)).height / 800f));
		float num3 = ((num >= 1f) ? Mathf.Min(num2, Mathf.Floor(num)) : Mathf.Max(0.01f, num));
		((Transform)window).localScale = Vector3.one * num3;
		float num4 = (((Rect)(ref rect)).width - 504f * num3) * 0.5f;
		float num5 = (((Rect)(ref rect)).height - 482f * num3) * 0.5f;
		window.anchoredPosition = new Vector2(Mathf.Round(num4) - num4, Mathf.Round(num5) - num5);
	}

	private static int BySeat(PlayerController a, PlayerController b)
	{
		int num = a.index.CompareTo(b.index);
		if (num != 0)
		{
			return num;
		}
		return ((NetworkBehaviour)a).netId.CompareTo(((NetworkBehaviour)b).netId);
	}

	private void Refresh()
	{
		//IL_038f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0388: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)amount == (Object)null || (Object)(object)send == (Object)null)
		{
			return;
		}
		if (seenSuccess != Wire.LastSuccess)
		{
			seenSuccess = Wire.LastSuccess;
			amount.SetTextWithoutNotify("");
		}
		local = (((Object)(object)NetworkClient.localPlayer != (Object)null) ? ((Component)NetworkClient.localPlayer).GetComponent<PlayerController>() : null);
		bool isLocalHost = OfflineWallets.IsLocalHost;
		if (((Component)offlineBody).gameObject.activeSelf && !isLocalHost)
		{
			ShowWalletTab(WalletTab.Transfers);
		}
		((Component)offlineEntry).gameObject.SetActive(isLocalHost && ((Component)sendBody).gameObject.activeSelf);
		((Selectable)offlineEntry).interactable = !Wire.Waiting;
		bool flag = (Object)(object)local != (Object)null && local.balanceKnown;
		balance.text = (flag ? Money.ExactGrouped(local.balanceCents) : "…");
		if (((Component)freeBody).gameObject.activeSelf)
		{
			RefreshFreeBudget();
			return;
		}
		if (((Component)offlineBody).gameObject.activeSelf)
		{
			RefreshOffline();
			return;
		}
		others.Clear();
		if ((Object)(object)local != (Object)null && (Object)(object)GameManager.instance != (Object)null)
		{
			foreach (PlayerController player in GameManager.instance.players)
			{
				if ((Object)(object)player != (Object)null && (Object)(object)player != (Object)(object)local && player.steamId != local.steamId && Wallets.PersonalId(player.steamId) && ((NetworkBehaviour)player).netId != 0 && NetworkClient.spawned.ContainsKey(((NetworkBehaviour)player).netId))
				{
					others.Add(player);
				}
			}
		}
		others.Sort(BySeat);
		if ((Object)(object)FindSelected() == (Object)null)
		{
			selected = 0u;
		}
		int num = Math.Max(1, (others.Count + 4 - 1) / 4);
		page = Mathf.Clamp(page, 0, num - 1);
		pageLabel.text = page + 1 + " / " + num;
		((Selectable)previous).interactable = !Wire.Waiting && page > 0;
		((Selectable)next).interactable = !Wire.Waiting && page + 1 < num;
		((Component)empty).gameObject.SetActive(others.Count == 0);
		for (int i = 0; i < 4; i++)
		{
			int num2 = page * 4 + i;
			bool flag2 = num2 < others.Count;
			((Component)rows[i]).gameObject.SetActive(flag2);
			if (flag2)
			{
				PlayerController val = others[num2];
				((Selectable)rows[i]).interactable = !Wire.Waiting;
				rowText[i].text = val.index + 1 + "   " + Wallets.Display(val);
				SetColors(rows[i], (((NetworkBehaviour)val).netId == selected) ? Teal : Surface);
			}
		}
		((Selectable)amount).interactable = !Wire.Waiting && Wire.HostSupportsWallets;
		int cents;
		bool flag3 = MoneyRules.TryReadAmount(amount.text, out cents);
		bool flag4 = flag3 && flag && cents <= local.balanceCents;
		((Selectable)send).interactable = Wire.HostSupportsWallets && !Wire.Waiting && selected != 0 && flag4;
		if (!Wire.HostSupportsWallets)
		{
			status.text = (Wire.ProbeFinished ? "The host needs Separate Wallets for transfers." : "Checking the host’s wallet settings…");
			return;
		}
		if (Wire.Feedback.Length != 0)
		{
			status.text = Wire.Feedback;
			return;
		}
		if (others.Count == 0)
		{
			status.text = "";
			return;
		}
		if (selected == 0)
		{
			status.text = "Choose a player to receive your transfer.";
			return;
		}
		if (string.IsNullOrWhiteSpace(amount.text))
		{
			status.text = "Enter an amount, for example 12.50.";
			return;
		}
		if (!flag3)
		{
			status.text = "Enter a positive amount with up to two decimal places.";
			return;
		}
		if (!flag4)
		{
			status.text = "Your balance is too low for this transfer.";
			return;
		}
		status.text = "Send " + Money.ExactGrouped(cents) + " to " + Wallets.Display(FindSelected()) + ".";
	}

	private PlayerController FindSelected()
	{
		if (selected != 0)
		{
			foreach (PlayerController other in others)
			{
				if ((Object)(object)other != (Object)null && ((NetworkBehaviour)other).netId == selected)
				{
					return other;
				}
			}
		}
		return null;
	}

	private void Select(int row)
	{
		int num = page * 4 + row;
		if (!Wire.Waiting && num < others.Count && !((Object)(object)others[num] == (Object)null))
		{
			selected = ((NetworkBehaviour)others[num]).netId;
			Wire.ClearFeedback();
			Refresh();
		}
	}

	private void ChangePage(int step)
	{
		if (!Wire.Waiting)
		{
			page += step;
			selected = 0u;
			Wire.ClearFeedback();
			Refresh();
		}
	}

	private void Send()
	{
		PlayerController val = FindSelected();
		if ((Object)(object)val != (Object)null && MoneyRules.TryReadAmount(amount.text, out var cents))
		{
			Wire.Submit(val, cents);
		}
		Refresh();
	}

	private TMP_InputField MakeAmount(RectTransform parent)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		RectTransform obj = Box(parent, "Amount", 24f, 363f, 282f, 48f);
		Image targetGraphic = Fill(obj, Paper);
		TMP_InputField val = ((Component)obj).gameObject.AddComponent<TMP_InputField>();
		((Selectable)val).targetGraphic = (Graphic)(object)targetGraphic;
		RectTransform val2 = Node(obj, "Text viewport");
		Stretch(val2, 12f, 4f);
		((Component)val2).gameObject.AddComponent<RectMask2D>();
		TextMeshProUGUI placeholder = Label(val2, "0.00", 22f, Surface, (FontStyles)0, (TextAlignmentOptions)513);
		TextMeshProUGUI textComponent = Label(val2, "", 22f, Ink, (FontStyles)0, (TextAlignmentOptions)513);
		val.textViewport = val2;
		val.textComponent = (TMP_Text)(object)textComponent;
		val.placeholder = (Graphic)(object)placeholder;
		val.lineType = (LineType)0;
		val.characterLimit = 16;
		val.richText = false;
		val.customCaretColor = true;
		val.caretColor = Ink;
		return val;
	}

	private Button MakeButton(RectTransform parent, string text, UnityAction click, float x, float y, float width, float height, Color background, Color foreground)
	{
		//IL_0011: 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_004a: Unknown result type (might be due to invalid IL or missing references)
		RectTransform val = Box(parent, text, x, y, width, height);
		Image targetGraphic = Fill(val, Color.white);
		Button obj = ((Component)val).gameObject.AddComponent<Button>();
		((Selectable)obj).targetGraphic = (Graphic)(object)targetGraphic;
		SetColors(obj, background);
		((UnityEvent)obj.onClick).AddListener(click);
		Label(val, text, 19f, foreground, (FontStyles)1, (TextAlignmentOptions)514);
		return obj;
	}

	private static void SetColors(Button button, Color normal)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: 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_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: 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_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: 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_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: 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)
		ColorBlock colors = ((Selectable)button).colors;
		((ColorBlock)(ref colors)).normalColor = normal;
		((ColorBlock)(ref colors)).highlightedColor = Color.Lerp(normal, Color.white, 0.16f);
		((ColorBlock)(ref colors)).selectedColor = Color.Lerp(normal, Color.white, 0.1f);
		((ColorBlock)(ref colors)).pressedColor = Color.Lerp(normal, Color.black, 0.16f);
		((ColorBlock)(ref colors)).disabledColor = Color.Lerp(normal, Ink, 0.55f);
		((ColorBlock)(ref colors)).fadeDuration = 0.08f;
		((ColorBlock)(ref colors)).colorMultiplier = 1f;
		((Selectable)button).colors = colors;
	}

	private TMP_Text MakeText(RectTransform parent, string text, float x, float y, float width, float height, float size, Color color, FontStyles style = (FontStyles)0, TextAlignmentOptions alignment = (TextAlignmentOptions)513)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		return (TMP_Text)(object)Label(Box(parent, "Label", x, y, width, height), text, size, color, style, alignment);
	}

	private TextMeshProUGUI Label(RectTransform parent, string text, float size, Color color, FontStyles style, TextAlignmentOptions alignment)
	{
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		RectTransform obj = Node(parent, "Text");
		Stretch(obj);
		TextMeshProUGUI val = ((Component)obj).gameObject.AddComponent<TextMeshProUGUI>();
		if ((Object)(object)font != (Object)null)
		{
			((TMP_Text)val).font = font;
		}
		((TMP_Text)val).fontSize = size;
		((TMP_Text)val).fontStyle = style;
		((TMP_Text)val).alignment = alignment;
		((Graphic)val).color = color;
		((TMP_Text)val).richText = false;
		((TMP_Text)val).textWrappingMode = (TextWrappingModes)0;
		((TMP_Text)val).overflowMode = (TextOverflowModes)1;
		((Graphic)val).raycastTarget = false;
		((TMP_Text)val).text = text;
		return val;
	}

	private static RectTransform Node(RectTransform parent, string name)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Expected O, but got Unknown
		RectTransform val = (RectTransform)new GameObject(name, new Type[1] { typeof(RectTransform) }).transform;
		((Component)val).gameObject.layer = ((Component)parent).gameObject.layer;
		((Transform)val).SetParent((Transform)(object)parent, false);
		return val;
	}

	private static RectTransform Box(RectTransform parent, string name, float x, float y, float width, float height)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: 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_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: 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)
		RectTransform obj = Node(parent, name);
		Vector2 val = default(Vector2);
		((Vector2)(ref val))..ctor(0f, 1f);
		obj.pivot = val;
		Vector2 anchorMin = (obj.anchorMax = val);
		obj.anchorMin = anchorMin;
		obj.sizeDelta = new Vector2(width, height);
		obj.anchoredPosition = new Vector2(x, 0f - y);
		return obj;
	}

	private static void Stretch(RectTransform r, float horizontal = 0f, float vertical = 0f)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: 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)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		r.anchorMin = Vector2.zero;
		r.anchorMax = Vector2.one;
		r.offsetMin = new Vector2(horizontal, vertical);
		r.offsetMax = new Vector2(0f - horizontal, 0f - vertical);
	}

	private static Image Fill(RectTransform r, Color color)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		Image obj = ((Component)r).gameObject.AddComponent<Image>();
		((Graphic)obj).color = color;
		return obj;
	}

	private void BuildFreeBudgetMenu()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Expected O, but got Unknown
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: 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_01f5: 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_0266: Unknown result type (might be due to invalid IL or missing references)
		//IL_027f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0284: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Expected O, but got Unknown
		//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cf: Expected O, but got Unknown
		freeEntry = MakeButton(card, "Free Budget", new UnityAction(OpenFreeBudget), 136f, 23f, 132f, 34f, Surface, Paper);
		freeBody = Node(card, "Free Budget");
		Stretch(freeBody);
		((Component)freeBody).gameObject.SetActive(false);
		MakeText(freeBody, "Free Budget", 24f, 127f, 456f, 34f, 24f, Paper, (FontStyles)1, (TextAlignmentOptions)513);
		MakeText(freeBody, "Available to the crew", 24f, 173f, 246f, 30f, 18f, Muted, (FontStyles)0, (TextAlignmentOptions)513);
		markedValue = MakeText(freeBody, "", 276f, 169f, 204f, 36f, 24f, Lime, (FontStyles)1, (TextAlignmentOptions)516);
		MakeText(freeBody, "Share of future earnings", 24f, 220f, 318f, 32f, 19f, Paper, (FontStyles)0, (TextAlignmentOptions)513);
		rateValue = MakeText(freeBody, "", 350f, 217f, 130f, 36f, 24f, Lime, (FontStyles)1, (TextAlignmentOptions)516);
		freeRate = MakeSlider(freeBody, "Income percentage", 262f, 100, wholeNumbers: true);
		((UnityEvent<float>)(object)freeRate.onValueChanged).AddListener((UnityAction<float>)delegate(float value)
		{
			draftRate = Mathf.RoundToInt(value);
			RefreshFreeBudget();
		});
		MakeText(freeBody, "0% stops new contributions. Existing holdings stay available until spent or released.", 24f, 318f, 456f, 50f, 17f, Muted, (FontStyles)0, (TextAlignmentOptions)513).textWrappingMode = (TextWrappingModes)1;
		freeStatus = MakeText(freeBody, "", 24f, 371f, 456f, 28f, 16f, Muted, (FontStyles)0, (TextAlignmentOptions)513);
		freeStatus.textWrappingMode = (TextWrappingModes)1;
		freeRelease = MakeButton(freeBody, "Release holdings", (UnityAction)delegate
		{
			FreeBudgetNet.SubmitRelease();
			RefreshFreeBudget();
		}, 24f, 406f, 240f, 42f, Surface, Paper);
		freeApply = MakeButton(freeBody, "Apply rate", (UnityAction)delegate
		{
			FreeBudgetNet.Submit(draftRate);
			if (FreeBudgetNet.PendingRate >= 0)
			{
				draftRate = -1;
			}
			RefreshFreeBudget();
		}, 278f, 406f, 202f, 42f, Lime, Ink);
	}

	private void OpenFreeBudget()
	{
		ShowWalletTab(WalletTab.FreeBudget);
		Refresh();
		if ((Object)(object)EventSystem.current != (Object)null)
		{
			EventSystem.current.SetSelectedGameObject(((Selectable)freeRate).interactable ? ((Component)freeRate).gameObject : ((Component)back).gameObject);
		}
	}

	private void RefreshFreeBudget()
	{
		bool ready = FreeBudgetNet.Ready;
		bool waiting = FreeBudgetNet.Waiting;
		int percent = FreeBudgetNet.View.Percent;
		int num = ((FreeBudgetNet.PendingRate >= 0) ? FreeBudgetNet.PendingRate : ((draftRate >= 0) ? draftRate : (ready ? percent : 10)));
		freeRate.SetValueWithoutNotify((float)num);
		((Selectable)freeRate).interactable = ready && !waiting;
		((Selectable)freeApply).interactable = ready && !waiting && draftRate >= 0 && draftRate != percent;
		((Selectable)freeRelease).interactable = ready && !waiting && FreeBudgetNet.View.Marked > 0;
		rateValue.text = (ready ? (num + "%") : "…");
		markedValue.text = (ready ? Money.ExactGrouped(FreeBudgetNet.View.Marked) : "…");
		if (!ready)
		{
			freeStatus.text = "Waiting for a host with Separate Wallets 0.4.2 or later.";
		}
		else if (waiting)
		{
			freeStatus.text = (FreeBudgetNet.PendingRelease ? "Releasing holdings…" : "Saving rate…");
		}
		else if (((Selectable)freeApply).interactable)
		{
			freeStatus.text = "Current rate " + percent + "%";
		}
		else
		{
			freeStatus.text = FreeBudgetNet.Feedback;
		}
	}

	internal static bool LocksCamera(PlayerCamera camera)
	{
		if (!IsVisible || (Object)(object)NetworkClient.localPlayer == (Object)null)
		{
			return false;
		}
		PlayerController component = ((Component)NetworkClient.localPlayer).GetComponent<PlayerController>();
		if ((Object)(object)component != (Object)null && (Object)(object)component.player != (Object)null)
		{
			return (Object)(object)component.player.GetCamera() == (Object)(object)camera;
		}
		return false;
	}

	internal static void ToggleWallet()
	{
		GameMenu instance = GameMenu.instance;
		if ((Object)(object)instance == (Object)null || !NetworkClient.ready || (Object)(object)NetworkClient.localPlayer == (Object)null || KeybindPanel.IsRebinding)
		{
			return;
		}
		if (IsVisible)
		{
			instance.Close();
			return;
		}
		if ((Object)(object)EventSystem.current != (Object)null && (Object)(object)EventSystem.current.currentSelectedGameObject != (Object)null)
		{
			TMP_InputField component = EventSystem.current.currentSelectedGameObject.GetComponent<TMP_InputField>();
			if (component != null && component.isFocused)
			{
				return;
			}
		}
		if ((Object)(object)UpgradePanel.Instance != (Object)null && UpgradePanel.Instance.IsOpen)
		{
			UpgradePanel.Instance.CloseToGame();
		}
		if ((Object)(object)BotPanel.Instance != (Object)null && BotPanel.Instance.IsOpen)
		{
			BotPanel.Instance.CloseToGame();
		}
		if (!instance.IsOpen)
		{
			if ((Object)(object)((Component)NetworkClient.localPlayer).GetComponent<PlayerController>()?.player == (Object)null || GameEndController.IsGameOver)
			{
				return;
			}
			instance.Open();
		}
		WalletMenu component2 = ((Component)instance).GetComponent<WalletMenu>();
		if ((Object)(object)component2 != (Object)null && (Object)(object)component2.budgetPanel != (Object)null)
		{
			component2.OpenWallet();
		}
	}

	private void OpenFunding()
	{
		Show.Invoke(menu, new object[1] { budgetPanel });
		RenderBudget();
		Focus(budgetClose);
	}

	internal CanvasGroup BuildBudgetPanel()
	{
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: 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_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0121: Unknown result type (might be due to invalid IL or missing references)
		//IL_0145: Unknown result type (might be due to invalid IL or missing references)
		//IL_015e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0163: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: Expected O, but got Unknown
		//IL_0187: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: Expected O, but got Unknown
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		//IL_0221: Unknown result type (might be due to invalid IL or missing references)
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_027e: Unknown result type (might be due to invalid IL or missing references)
		//IL_02af: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_034d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0366: Unknown result type (might be due to invalid IL or missing references)
		//IL_036b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0375: Expected O, but got Unknown
		//IL_03cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0406: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b8: Expected O, but got Unknown
		RectTransform val = Node(screenRoot, "Crew funding");
		Stretch(val);
		budgetPanel = ((Component)val).gameObject.AddComponent<CanvasGroup>();
		((Component)val).gameObject.SetActive(false);
		Fill(val, Color32.op_Implicit(new Color32((byte)10, (byte)17, (byte)20, (byte)225)));
		budgetCard = Node(val, "Funding");
		RectTransform obj = budgetCard;
		RectTransform obj2 = budgetCard;
		RectTransform obj3 = budgetCard;
		Vector2 val2 = default(Vector2);
		((Vector2)(ref val2))..ctor(0.5f, 0.5f);
		obj3.pivot = val2;
		Vector2 anchorMin = (obj2.anchorMax = val2);
		obj.anchorMin = anchorMin;
		budgetCard.sizeDelta = new Vector2(504f, 482f);
		Fill(budgetCard, Ink);
		Fill(Box(budgetCard, "Accent", 0f, 0f, 504f, 4f), Lime);
		MakeText(budgetCard, "Crew funding", 24f, 14f, 245f, 48f, 32f, Paper, (FontStyles)1, (TextAlignmentOptions)513);
		MakeButton(budgetCard, "Back", new UnityAction(OpenWallet), 278f, 22f, 108f, 34f, Surface, Paper);
		budgetClose = MakeButton(budgetCard, "Close", new UnityAction(menu.Close), 396f, 22f, 84f, 34f, Surface, Paper);
		subject = MakeText(budgetCard, "", 24f, 72f, 456f, 56f, 22f, Paper, (FontStyles)1, (TextAlignmentOptions)513);
		subject.textWrappingMode = (TextWrappingModes)1;
		progress = MakeText(budgetCard, "", 24f, 139f, 456f, 34f, 19f, Paper, (FontStyles)0, (TextAlignmentOptions)513);
		RectTransform val4 = Box(budgetCard, "Funding progress", 24f, 183f, 456f, 14f);
		Fill(val4, Surface);
		funded = Node(val4, "Confirmed contributions");
		Fill(funded, Lime);
		countdown = MakeText(budgetCard, "", 24f, 205f, 456f, 31f, 16f, Muted, (FontStyles)0, (TextAlignmentOptions)513);
		myBudget = MakeText(budgetCard, "", 24f, 256f, 456f, 36f, 20f, Paper, (FontStyles)0, (TextAlignmentOptions)513);
		pledge = MakeSlider(budgetCard, "Pledge amount", 298f, 1, wholeNumbers: false);
		((UnityEvent<float>)(object)pledge.onValueChanged).AddListener((UnityAction<float>)delegate(float v)
		{
			FundingNet.Draft = (int)Math.Floor((double)v * (double)PledgeLimit() + 0.5);
			RenderBudget();
		});
		commit = MakeButton(budgetCard, "Confirm pledge", new UnityAction(SubmitPledge), 24f, 352f, 259f, 42f, Lime, Ink);
		commitText = ((Component)commit).GetComponentInChildren<TMP_Text>(true);
		RectTransform parent = budgetCard;
		object obj4 = <>c.<>9__85_1;
		if (obj4 == null)
		{
			UnityAction val5 = delegate
			{
				FundingNet.Submit(3);
			};
			<>c.<>9__85_1 = val5;
			obj4 = (object)val5;
		}
		cancelBudget = MakeButton(parent, "Cancel request", (UnityAction)obj4, 292f, 352f, 188f, 42f, Surface, Paper);
		feedback = MakeText(budgetCard, "", 24f, 399f, 456f, 72f, 16f, Muted, (FontStyles)0, (TextAlignmentOptions)513);
		feedback.textWrappingMode = (TextWrappingModes)1;
		return budgetPanel;
	}

	private Slider MakeSlider(RectTransform parent, string name, float y, int maximum, bool wholeNumbers)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: 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_008e: 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)
		RectTransform obj = Box(parent, name, 24f, y, 456f, 42f);
		Fill(obj, Color32.op_Implicit(new Color32((byte)32, (byte)49, (byte)52, byte.MaxValue)));
		Fill(Box(obj, "Track", 10f, 18f, 436f, 6f), Teal);
		RectTransform obj2 = Node(obj, "Handle area");
		Stretch(obj2, 10f);
		RectTransform val = Node(obj2, "Handle");
		val.sizeDelta = new Vector2(18f, -10f);
		Image targetGraphic = Fill(val, Lime);
		Slider obj3 = ((Component)obj).gameObject.AddComponent<Slider>();
		obj3.handleRect = val;
		((Selectable)obj3).targetGraphic = (Graphic)(object)targetGraphic;
		obj3.minValue = 0f;
		obj3.maxValue = maximum;
		obj3.wholeNumbers = wholeNumbers;
		return obj3;
	}

	private static int PledgeLimit()
	{
		PlayerController val = (((Object)(object)NetworkClient.localPlayer != (Object)null) ? ((Component)NetworkClient.localPlayer).GetComponent<PlayerController>() : null);
		return Math.Max(0, Math.Min(FundingNet.View.Left, ((Object)(object)val != (Object)null) ? val.balanceCents : 0));
	}

	private void SubmitPledge()
	{
		if (FundingNet.View.Mine > 0)
		{
			FundingNet.Submit(2);
		}
		else
		{
			FundingNet.Submit(1, FundingNet.Draft);
		}
	}

	private void RenderBudget()
	{
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: 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_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		Fit(budgetCard);
		FundingState view = FundingNet.View;
		bool flag = view.Id != 0;
		int num = (int)Math.Max(0.0, Math.Ceiling(view.Deadline - NetworkTime.time));
		subject.text = (flag ? (view.Name + " · " + view.Item) : "No active funding request");
		progress.text = (flag ? (Money.ExactGrouped(view.Left) + " left of " + Money.ExactGrouped(view.Gap) + " needed") : "");
		funded.anchorMin = Vector2.zero;
		funded.anchorMax = new Vector2((flag && view.Gap > 0) ? (1f - (float)view.Left / (float)view.Gap) : 0f, 1f);
		RectTransform obj = funded;
		Vector2 offsetMin = (funded.offsetMax = Vector2.zero);
		obj.offsetMin = offsetMin;
		countdown.text = (flag ? ("Price " + Money.ExactGrouped(view.Price) + "    ·    " + num / 60 + ":" + (num % 60).ToString("00") + " left") : "");
		PlayerController val = (((Object)(object)NetworkClient.localPlayer != (Object)null) ? ((Component)NetworkClient.localPlayer).GetComponent<PlayerController>() : null);
		int num2 = (((Object)(object)val != (Object)null) ? Math.Max(0, val.balanceCents) : 0);
		int draft = FundingNet.Draft;
		((Component)pledge).gameObject.SetActive(flag && !view.Buyer);
		((Selectable)pledge).interactable = num > 0 && view.Mine == 0;
		int num3 = Math.Min(num2, view.Left);
		pledge.SetValueWithoutNotify((view.Mine > 0 || num3 <= 0) ? 0f : ((float)draft / (float)num3));
		myBudget.text = ((!flag) ? "" : (view.Buyer ? ("Your share: " + Money.ExactGrouped(view.Price - view.Gap)) : ((view.Mine > 0) ? ("Your confirmed pledge: " + Money.ExactGrouped(view.Mine)) : (((view.Left > 0) ? (100.0 * (double)draft / (double)view.Left).ToString("0.##") : "0") + "% of remaining · " + Money.ExactGrouped(draft)))));
		((Component)commit).gameObject.SetActive(flag && !view.Buyer);
		commitText.text = ((view.Mine > 0) ? "Unconfirm pledge" : "Confirm pledge");
		((Selectable)commit).interactable = num > 0 && (view.Mine > 0 || (draft > 0 && draft <= num2));
		((Component)cancelBudget).gameObject.SetActive(flag && view.Buyer);
		((Selectable)cancelBudget).interactable = num > 0;
		feedback.text = ((!FundingNet.Ready) ? "Waiting for a host running Separate Wallets 0.3.0 or later." : ((flag && !view.Buyer && view.Mine == 0 && draft > num2) ? ("Your wallet has " + Money.ExactGrouped(num2) + ". Choose a smaller pledge.") : FundingNet.Feedback));
	}

	private void BuildOfflineMenu()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Expected O, but got Unknown
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Expected O, but got Unknown
		//IL_012b: 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_016d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: Expected O, but got Unknown
		//IL_01b3: 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_01d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e1: Expected O, but got Unknown
		//IL_0226: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0268: Unknown result type (might be due to invalid IL or missing references)
		//IL_026d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0277: Expected O, but got Unknown
		//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
		offlineEntry = MakeButton(card, "Offline wallets", (UnityAction)delegate
		{
			if (OfflineWallets.IsLocalHost && !Wire.Waiting)
			{
				ShowWalletTab(WalletTab.Offline);
				Refresh();
				Focus((offers.Count == 0) ? back : offlineRows[0]);
			}
		}, 274f, 23f, 126f, 34f, Surface, Paper);
		((Component)offlineEntry).gameObject.SetActive(false);
		offlineBody = Node(card, "Offline wallets");
		Stretch(offlineBody);
		((Component)offlineBody).gameObject.SetActive(false);
		MakeText(offlineBody, "Offline wallets", 24f, 129f, 280f, 32f, 22f, Paper, (FontStyles)1, (TextAlignmentOptions)513);
		older = MakeButton(offlineBody, "‹", (UnityAction)delegate
		{
			PageOffline(-1);
		}, 331f, 129f, 34f, 30f, Surface, Paper);
		offlinePageLabel = MakeText(offlineBody, "", 366f, 129f, 77f, 30f, 14f, Muted, (FontStyles)0, (TextAlignmentOptions)514);
		newer = MakeButton(offlineBody, "›", (UnityAction)delegate
		{
			PageOffline(1);
		}, 446f, 129f, 34f, 30f, Surface, Paper);
		for (int num = 0; num < 4; num++)
		{
			int row = num;
			offlineRows[num] = MakeButton(offlineBody, "Wallet", (UnityAction)delegate
			{
				PickOffline