-
Notifications
You must be signed in to change notification settings - Fork 48
/
WalletConnect.cs
566 lines (473 loc) · 17.2 KB
/
WalletConnect.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using WalletConnectSharp.Core;
using WalletConnectSharp.Core.Models;
using WalletConnectSharp.Core.Network;
using WalletConnectSharp.Unity.Models;
using WalletConnectSharp.Unity.Network;
using WalletConnectSharp.Unity.Utils;
namespace WalletConnectSharp.Unity
{
[RequireComponent(typeof(NativeWebSocketTransport))]
public class WalletConnect : BindableMonoBehavior
{
public const string SessionKey = "__WALLETCONNECT_SESSION__";
public Dictionary<string, AppEntry> SupportedWallets
{
get;
private set;
}
public AppEntry SelectedWallet { get; set; }
public Wallets DefaultWallet;
[Serializable]
public class WalletConnectEventNoSession : UnityEvent { }
[Serializable]
public class WalletConnectEventWithSession : UnityEvent<WalletConnectUnitySession> { }
[Serializable]
public class WalletConnectEventWithSessionData : UnityEvent<WCSessionData> { }
public event EventHandler ConnectionStarted;
public event EventHandler NewSessionStarted;
[BindComponent]
private NativeWebSocketTransport _transport;
private static WalletConnect _instance;
public static WalletConnect Instance
{
get
{
return _instance;
}
}
public static WalletConnectUnitySession ActiveSession
{
get
{
return _instance.Session;
}
}
public string ConnectURL
{
get
{
return Protocol.URI;
}
}
public bool autoSaveAndResume = true;
public bool connectOnAwake = false;
public bool connectOnStart = true;
public bool createNewSessionOnSessionDisconnect = true;
public int connectSessionRetryCount = 3;
public string customBridgeUrl;
public int chainId = 1;
public WalletConnectEventNoSession ConnectedEvent;
public WalletConnectEventWithSessionData ConnectedEventSession;
public WalletConnectEventWithSession DisconnectedEvent;
public WalletConnectEventWithSession ConnectionFailedEvent;
public WalletConnectEventWithSession NewSessionConnected;
public WalletConnectEventWithSession ResumedSessionConnected;
public WalletConnectUnitySession Session
{
get;
private set;
}
[Obsolete("Use Session instead of Protocol")]
public WalletConnectUnitySession Protocol {
get { return Session; }
private set
{
Session = value;
}
}
public bool Connected
{
get
{
return Protocol.Connected;
}
}
[SerializeField]
public ClientMeta AppData;
protected override async void Awake()
{
if (_instance != null)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
_instance = this;
base.Awake();
if (connectOnAwake)
{
await Connect();
}
}
async void Start()
{
if (connectOnStart && !connectOnAwake)
{
await Connect();
}
}
public async Task<WCSessionData> Connect()
{
SavedSession savedSession = null;
if (PlayerPrefs.HasKey(SessionKey))
{
var json = PlayerPrefs.GetString(SessionKey);
savedSession = JsonConvert.DeserializeObject<SavedSession>(json);
}
if (string.IsNullOrWhiteSpace(customBridgeUrl))
{
customBridgeUrl = null;
}
if (Session != null)
{
var currentKey = Session.KeyData;
if (savedSession != null)
{
if (currentKey != savedSession.Key)
{
if (Session.Connected)
{
await Session.Disconnect();
}
else if (Session.TransportConnected)
{
await Session.Transport.Close();
}
}
else if (!Session.Connected && !Session.Connecting)
{
StartCoroutine(SetupDefaultWallet());
SetupEvents();
return await CompleteConnect();
}
else
{
return null; //Nothing to do
}
}
else if (Session.Connected)
{
await Session.Disconnect();
}
else if (Session.TransportConnected)
{
await Session.Transport.Close();
}
else if (Session.Connecting)
{
//We are still connecting, do nothing
return null;
}
}
//default will be set by library
ICipher ciper = null;
#if UNITY_WEBGL
ciper = new WebGlAESCipher();
#endif
if (savedSession != null)
{
Session = new WalletConnectUnitySession(savedSession, this, _transport);
}
else
{
Session = new WalletConnectUnitySession(AppData, this, customBridgeUrl, _transport, ciper, chainId);
if (NewSessionStarted != null)
NewSessionStarted(this, EventArgs.Empty);
}
StartCoroutine(SetupDefaultWallet());
SetupEvents();
return await CompleteConnect();
}
private void SetupEvents()
{
#if UNITY_EDITOR || DEBUG
//Useful for debug logging
Session.OnSessionConnect += (sender, session) =>
{
Debug.Log("[WalletConnect] Session Connected");
};
#endif
Session.OnSessionDisconnect += SessionOnOnSessionDisconnect;
Session.OnSessionCreated += SessionOnOnSessionCreated;
Session.OnSessionResumed += SessionOnOnSessionResumed;
#if UNITY_ANDROID || UNITY_IOS
//Whenever we send a request to the Wallet, we want to open the Wallet app
Session.OnSend += (sender, session) => OpenMobileWallet();
#endif
}
private void TeardownEvents()
{
Session.OnSessionDisconnect -= SessionOnOnSessionDisconnect;
Session.OnSessionCreated -= SessionOnOnSessionCreated;
Session.OnSessionResumed -= SessionOnOnSessionResumed;
}
private void SessionOnOnSessionResumed(object sender, WalletConnectSession e)
{
if (this.ResumedSessionConnected != null)
this.ResumedSessionConnected.Invoke(e as WalletConnectUnitySession ?? Session);
}
private void SessionOnOnSessionCreated(object sender, WalletConnectSession e)
{
if (this.NewSessionConnected != null)
this.NewSessionConnected.Invoke(e as WalletConnectUnitySession ?? Session);
}
private async Task<WCSessionData> CompleteConnect()
{
Debug.Log("Waiting for Wallet connection");
if (ConnectionStarted != null)
{
ConnectionStarted(this, EventArgs.Empty);
}
WalletConnectEventWithSessionData allEvents = new WalletConnectEventWithSessionData();
allEvents.AddListener(delegate(WCSessionData arg0)
{
ConnectedEvent.Invoke();
ConnectedEventSession.Invoke(arg0);
});
int tries = 0;
while (tries < connectSessionRetryCount)
{
try
{
var session = await Session.SourceConnectSession();
allEvents.Invoke(session);
return session;
}
catch (IOException e)
{
tries++;
if (tries >= connectSessionRetryCount)
throw new IOException("Failed to request session connection after " + tries + " times.", e);
}
}
throw new IOException("Failed to request session connection after " + tries + " times.");
}
private async void SessionOnOnSessionDisconnect(object sender, EventArgs e)
{
if (DisconnectedEvent != null)
DisconnectedEvent.Invoke(ActiveSession);
if (autoSaveAndResume && PlayerPrefs.HasKey(SessionKey))
{
PlayerPrefs.DeleteKey(SessionKey);
}
TeardownEvents();
if (createNewSessionOnSessionDisconnect)
{
await Connect();
}
}
private IEnumerator SetupDefaultWallet()
{
yield return FetchWalletList(false);
var wallet = SupportedWallets.Values.FirstOrDefault(a => a.name.ToLower() == DefaultWallet.ToString().ToLower());
if (wallet != null)
{
yield return DownloadImagesFor(wallet.id);
SelectedWallet = wallet;
Debug.Log("Setup default wallet " + wallet.name);
}
}
private IEnumerator DownloadImagesFor(string id, string[] sizes = null)
{
if (sizes == null)
{
sizes = new string[] {"sm", "md", "lg"};
}
var data = SupportedWallets[id];
foreach (var size in sizes)
{
var url = "https://registry.walletconnect.org/logo/" + size + "/" + id + ".jpeg";
using (UnityWebRequest imageRequest = UnityWebRequestTexture.GetTexture(url))
{
yield return imageRequest.SendWebRequest();
if (imageRequest.isNetworkError)
{
Debug.Log("Error Getting Wallet Icon: " + imageRequest.error);
}
else
{
var texture = ((DownloadHandlerTexture) imageRequest.downloadHandler).texture;
var sprite = Sprite.Create(texture,
new Rect(0.0f, 0.0f, texture.width, texture.height),
new Vector2(0.5f, 0.5f), 100.0f);
if (size == "sm")
{
data.smallIcon = sprite;
}
else if (size == "md")
{
data.medimumIcon = sprite;
}
else if (size == "lg")
{
data.largeIcon = sprite;
}
}
}
}
}
public IEnumerator FetchWalletList(bool downloadImages = true)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get("https://registry.walletconnect.org/data/wallets.json"))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError)
{
Debug.Log("Error Getting Wallet Info: " + webRequest.error);
}
else
{
var json = webRequest.downloadHandler.text;
SupportedWallets = JsonConvert.DeserializeObject<Dictionary<string, AppEntry>>(json);
if (downloadImages)
{
foreach (var id in SupportedWallets.Keys)
{
yield return DownloadImagesFor(id);
}
}
}
}
}
private async void OnDestroy()
{
await SaveOrDisconnect();
}
private async void OnApplicationQuit()
{
await SaveOrDisconnect();
}
private async void OnApplicationPause(bool pauseStatus)
{
if (pauseStatus)
{
await SaveOrDisconnect();
}
else if (PlayerPrefs.HasKey(SessionKey) && autoSaveAndResume)
{
await Connect();
}
}
private async Task SaveOrDisconnect()
{
if (!Session.Connected)
return;
if (autoSaveAndResume)
{
var session = Session.SaveSession();
var json = JsonConvert.SerializeObject(session);
PlayerPrefs.SetString(SessionKey, json);
await Session.Transport.Close();
}
else
{
await Session.Disconnect();
}
}
public void OpenMobileWallet(AppEntry selectedWallet)
{
SelectedWallet = selectedWallet;
OpenMobileWallet();
}
public void OpenDeepLink(AppEntry selectedWallet)
{
SelectedWallet = selectedWallet;
OpenDeepLink();
}
public void OpenMobileWallet()
{
#if UNITY_ANDROID
var signingURL = ConnectURL.Split('@')[0];
Application.OpenURL(signingURL);
#elif UNITY_IOS
if (SelectedWallet == null)
{
throw new NotImplementedException(
"You must use OpenMobileWallet(AppEntry) or set SelectedWallet on iOS!");
}
else
{
string url;
string encodedConnect = WebUtility.UrlEncode(ConnectURL);
if (!string.IsNullOrWhiteSpace(SelectedWallet.mobile.universal))
{
url = SelectedWallet.mobile.universal + "/wc?uri=" + encodedConnect;
}
else
{
url = SelectedWallet.mobile.native + (SelectedWallet.mobile.native.EndsWith(":") ? "//" : "/") +
"wc?uri=" + encodedConnect;
}
var signingUrl = url.Split('?')[0];
Debug.Log("Opening: " + signingUrl);
Application.OpenURL(signingUrl);
}
#else
Debug.Log("Platform does not support deep linking");
return;
#endif
}
public void OpenDeepLink()
{
if (!ActiveSession.ReadyForUserPrompt)
{
Debug.LogError("WalletConnectUnity.ActiveSession not ready for a user prompt" +
"\nWait for ActiveSession.ReadyForUserPrompt to be true");
return;
}
#if UNITY_ANDROID
Debug.Log("[WalletConnect] Opening URL: " + ConnectURL);
Application.OpenURL(ConnectURL);
#elif UNITY_IOS
if (SelectedWallet == null)
{
throw new NotImplementedException(
"You must use OpenDeepLink(AppEntry) or set SelectedWallet on iOS!");
}
else
{
string url;
string encodedConnect = WebUtility.UrlEncode(ConnectURL);
if (!string.IsNullOrWhiteSpace(SelectedWallet.mobile.universal))
{
url = SelectedWallet.mobile.universal + "/wc?uri=" + encodedConnect;
}
else
{
url = SelectedWallet.mobile.native + (SelectedWallet.mobile.native.EndsWith(":") ? "//" : "/") +
"wc?uri=" + encodedConnect;
}
Debug.Log("Opening: " + url);
Application.OpenURL(url);
}
#else
Debug.Log("Platform does not support deep linking");
return;
#endif
}
public void CLearSession()
{
PlayerPrefs.DeleteKey(SessionKey);
}
public async void CloseSession(bool waitForNewSession = true)
{
if (ActiveSession == null)
return;
await ActiveSession.Disconnect();
if (waitForNewSession)
await ActiveSession.Connect();
}
}
}