Skip to content

Commit 28e6508

Browse files
authored
Autoconnect Feature (#224)
1 parent c728323 commit 28e6508

File tree

2 files changed

+121
-15
lines changed

2 files changed

+121
-15
lines changed

Assets/Thirdweb/Editor/ThirdwebManagerEditor.cs

+7
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public class ThirdwebManagerEditor : UnityEditor.Editor
1313
private SerializedProperty initializeOnAwakeProp;
1414
private SerializedProperty showDebugLogsProp;
1515
private SerializedProperty optOutUsageAnalyticsProp;
16+
private SerializedProperty autoConnectLastWallet;
1617
private SerializedProperty supportedChainsProp;
1718
private SerializedProperty includedWalletIdsProp;
1819
private SerializedProperty redirectPageHtmlOverrideProp;
@@ -33,6 +34,7 @@ private void OnEnable()
3334
initializeOnAwakeProp = FindProperty("InitializeOnAwake");
3435
showDebugLogsProp = FindProperty("ShowDebugLogs");
3536
optOutUsageAnalyticsProp = FindProperty("OptOutUsageAnalytics");
37+
autoConnectLastWallet = FindProperty("AutoConnectLastWallet");
3638
supportedChainsProp = FindProperty("SupportedChains");
3739
includedWalletIdsProp = FindProperty("IncludedWalletIds");
3840
redirectPageHtmlOverrideProp = FindProperty("RedirectPageHtmlOverride");
@@ -158,6 +160,11 @@ private void DrawPreferencesTab()
158160
DrawProperty(initializeOnAwakeProp, "Initialize On Awake", "If enabled, Thirdweb will initialize on Awake. If disabled, you must call ThirdwebManager.Instance.Initialize() manually.");
159161
DrawProperty(showDebugLogsProp, "Show Debug Logs", "If enabled, Thirdweb will log debug messages to the console.");
160162
DrawProperty(optOutUsageAnalyticsProp, "Opt-Out of Usage Analytics", "If enabled, you may see inconsistent stats in your Thirdweb Dashboard.");
163+
DrawProperty(
164+
autoConnectLastWallet,
165+
"Auto-Connect Last Wallet",
166+
"If enabled, Thirdweb will automatically connect to the last connected wallet on initialization (this behavior does not apply to the WalletConnectWallet provider option)."
167+
);
161168
}
162169

163170
private void DrawMiscTab()

Assets/Thirdweb/Runtime/Unity/ThirdwebManager.cs

+114-15
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
using System.Linq;
66
using System;
77
using System.IO;
8+
using Newtonsoft.Json;
89

910
namespace Thirdweb.Unity
1011
{
12+
[Serializable]
1113
public enum WalletProvider
1214
{
1315
PrivateKeyWallet,
@@ -17,6 +19,7 @@ public enum WalletProvider
1719
EcosystemWallet
1820
}
1921

22+
[Serializable]
2023
public class InAppWalletOptions : EcosystemWalletOptions
2124
{
2225
public InAppWalletOptions(
@@ -39,16 +42,34 @@ public InAppWalletOptions(
3942
) { }
4043
}
4144

45+
[Serializable]
4246
public class EcosystemWalletOptions
4347
{
48+
[JsonProperty("ecosystemId")]
4449
public string EcosystemId;
50+
51+
[JsonProperty("ecosystemPartnerId")]
4552
public string EcosystemPartnerId;
53+
54+
[JsonProperty("email")]
4655
public string Email;
56+
57+
[JsonProperty("phoneNumber")]
4758
public string PhoneNumber;
59+
60+
[JsonProperty("authProvider")]
4861
public AuthProvider AuthProvider;
62+
63+
[JsonProperty("jwtOrPayload")]
4964
public string JwtOrPayload;
65+
66+
[JsonProperty("storageDirectoryPath")]
5067
public string StorageDirectoryPath;
68+
69+
[JsonProperty("siweSigner")]
5170
public IThirdwebWallet SiweSigner;
71+
72+
[JsonProperty("legacyEncryptionKey")]
5273
public string LegacyEncryptionKey;
5374

5475
public EcosystemWalletOptions(
@@ -75,14 +96,28 @@ public EcosystemWalletOptions(
7596
}
7697
}
7798

99+
[Serializable]
78100
public class SmartWalletOptions
79101
{
102+
[JsonProperty("sponsorGas")]
80103
public bool SponsorGas;
104+
105+
[JsonProperty("factoryAddress")]
81106
public string FactoryAddress;
107+
108+
[JsonProperty("accountAddressOverride")]
82109
public string AccountAddressOverride;
110+
111+
[JsonProperty("entryPoint")]
83112
public string EntryPoint;
113+
114+
[JsonProperty("bundlerUrl")]
84115
public string BundlerUrl;
116+
117+
[JsonProperty("paymasterUrl")]
85118
public string PaymasterUrl;
119+
120+
[JsonProperty("tokenPaymaster")]
86121
public TokenPaymaster TokenPaymaster;
87122

88123
public SmartWalletOptions(
@@ -105,12 +140,22 @@ public SmartWalletOptions(
105140
}
106141
}
107142

143+
[Serializable]
108144
public class WalletOptions
109145
{
146+
[JsonProperty("provider")]
110147
public WalletProvider Provider;
148+
149+
[JsonProperty("chainId")]
111150
public BigInteger ChainId;
151+
152+
[JsonProperty("inAppWalletOptions")]
112153
public InAppWalletOptions InAppWalletOptions;
154+
155+
[JsonProperty("ecosystemWalletOptions", NullValueHandling = NullValueHandling.Ignore)]
113156
public EcosystemWalletOptions EcosystemWalletOptions;
157+
158+
[JsonProperty("smartWalletOptions", NullValueHandling = NullValueHandling.Ignore)]
114159
public SmartWalletOptions SmartWalletOptions;
115160

116161
public WalletOptions(
@@ -154,6 +199,9 @@ public class ThirdwebManager : MonoBehaviour
154199
[field: SerializeField]
155200
private bool OptOutUsageAnalytics { get; set; } = false;
156201

202+
[field: SerializeField]
203+
private bool AutoConnectLastWallet { get; set; } = false;
204+
157205
[field: SerializeField]
158206
private ulong[] SupportedChains { get; set; } = new ulong[] { 421614 };
159207

@@ -170,11 +218,13 @@ public class ThirdwebManager : MonoBehaviour
170218

171219
public IThirdwebWallet ActiveWallet { get; private set; }
172220

221+
public bool Initialized { get; private set; }
222+
173223
public static ThirdwebManager Instance { get; private set; }
174224

175225
public static readonly string THIRDWEB_UNITY_SDK_VERSION = "5.14.0";
176226

177-
private bool _initialized;
227+
private const string THIRDWEB_AUTO_CONNECT_OPTIONS_KEY = "ThirdwebAutoConnectOptions";
178228

179229
private Dictionary<string, IThirdwebWallet> _walletMapping;
180230

@@ -199,7 +249,7 @@ private void Awake()
199249
}
200250
}
201251

202-
public void Initialize()
252+
public async void Initialize()
203253
{
204254
if (string.IsNullOrEmpty(ClientId))
205255
{
@@ -229,12 +279,26 @@ public void Initialize()
229279

230280
_walletMapping = new Dictionary<string, IThirdwebWallet>();
231281

232-
_initialized = true;
282+
if (AutoConnectLastWallet && GetAutoConnectOptions(out var lastWalletOptions))
283+
{
284+
ThirdwebDebug.Log("Auto-connecting to last wallet.");
285+
try
286+
{
287+
_ = await ConnectWallet(lastWalletOptions);
288+
ThirdwebDebug.Log("Auto-connected to last wallet.");
289+
}
290+
catch (Exception e)
291+
{
292+
ThirdwebDebug.LogError("Failed to auto-connect to last wallet: " + e.Message);
293+
}
294+
}
295+
296+
Initialized = true;
233297
}
234298

235299
public async Task<ThirdwebContract> GetContract(string address, BigInteger chainId, string abi = null)
236300
{
237-
if (!_initialized)
301+
if (!Initialized)
238302
{
239303
throw new InvalidOperationException("ThirdwebManager is not initialized.");
240304
}
@@ -279,11 +343,6 @@ public void RemoveWallet(string address)
279343

280344
public async Task<IThirdwebWallet> ConnectWallet(WalletOptions walletOptions)
281345
{
282-
if (!_initialized)
283-
{
284-
throw new InvalidOperationException("ThirdwebManager is not initialized.");
285-
}
286-
287346
if (walletOptions == null)
288347
{
289348
throw new ArgumentNullException(nameof(walletOptions));
@@ -420,7 +479,6 @@ public async Task<IThirdwebWallet> ConnectWallet(WalletOptions walletOptions)
420479
}
421480

422481
var address = await wallet.GetAddress();
423-
ThirdwebDebug.Log($"Wallet address: {address}");
424482

425483
var isSmartWallet = walletOptions.SmartWalletOptions != null;
426484

@@ -429,6 +487,8 @@ public async Task<IThirdwebWallet> ConnectWallet(WalletOptions walletOptions)
429487
TrackUsage("connectWallet", "connect", isSmartWallet ? "smartWallet" : walletOptions.Provider.ToString()[..1].ToLower() + walletOptions.Provider.ToString()[1..], address);
430488
}
431489

490+
SetAutoConnectOptions(walletOptions);
491+
432492
if (isSmartWallet)
433493
{
434494
ThirdwebDebug.Log("Upgrading to SmartWallet.");
@@ -444,11 +504,6 @@ public async Task<IThirdwebWallet> ConnectWallet(WalletOptions walletOptions)
444504

445505
public async Task<SmartWallet> UpgradeToSmartWallet(IThirdwebWallet personalWallet, BigInteger chainId, SmartWalletOptions smartWalletOptions)
446506
{
447-
if (!_initialized)
448-
{
449-
throw new InvalidOperationException("ThirdwebManager is not initialized.");
450-
}
451-
452507
if (personalWallet.AccountType == ThirdwebAccountType.SmartAccount)
453508
{
454509
ThirdwebDebug.LogWarning("Wallet is already a SmartWallet.");
@@ -480,6 +535,12 @@ public async Task<SmartWallet> UpgradeToSmartWallet(IThirdwebWallet personalWall
480535
await AddWallet(wallet);
481536
SetActiveWallet(wallet);
482537

538+
if (AutoConnectLastWallet && GetAutoConnectOptions(out var lastWalletOptions))
539+
{
540+
lastWalletOptions.SmartWalletOptions = smartWalletOptions;
541+
SetAutoConnectOptions(lastWalletOptions);
542+
}
543+
483544
return wallet;
484545
}
485546

@@ -498,6 +559,44 @@ public async Task<List<LinkedAccount>> LinkAccount(IThirdwebWallet mainWallet, I
498559
);
499560
}
500561

562+
private bool GetAutoConnectOptions(out WalletOptions lastWalletOptions)
563+
{
564+
var connectOptionsStr = PlayerPrefs.GetString(THIRDWEB_AUTO_CONNECT_OPTIONS_KEY, null);
565+
if (!string.IsNullOrEmpty(connectOptionsStr))
566+
{
567+
try
568+
{
569+
lastWalletOptions = JsonConvert.DeserializeObject<WalletOptions>(connectOptionsStr);
570+
return true;
571+
}
572+
catch
573+
{
574+
ThirdwebDebug.LogWarning("Failed to load last wallet options.");
575+
PlayerPrefs.DeleteKey(THIRDWEB_AUTO_CONNECT_OPTIONS_KEY);
576+
lastWalletOptions = null;
577+
return false;
578+
}
579+
}
580+
lastWalletOptions = null;
581+
return false;
582+
}
583+
584+
private void SetAutoConnectOptions(WalletOptions walletOptions)
585+
{
586+
if (AutoConnectLastWallet && walletOptions.Provider != WalletProvider.WalletConnectWallet)
587+
{
588+
try
589+
{
590+
PlayerPrefs.SetString(THIRDWEB_AUTO_CONNECT_OPTIONS_KEY, JsonConvert.SerializeObject(walletOptions));
591+
}
592+
catch
593+
{
594+
ThirdwebDebug.LogWarning("Failed to save last wallet options.");
595+
PlayerPrefs.DeleteKey(THIRDWEB_AUTO_CONNECT_OPTIONS_KEY);
596+
}
597+
}
598+
}
599+
501600
private async void TrackUsage(string source, string action, string walletType, string walletAddress)
502601
{
503602
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(action) || string.IsNullOrEmpty(walletType) || string.IsNullOrEmpty(walletAddress))

0 commit comments

Comments
 (0)