-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathWalletConnectProvider.cs
More file actions
534 lines (450 loc) · 18.5 KB
/
WalletConnectProvider.cs
File metadata and controls
534 lines (450 loc) · 18.5 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChainSafe.Gaming.Evm;
using ChainSafe.Gaming.WalletConnect.Connection;
using ChainSafe.Gaming.WalletConnect.Methods;
using ChainSafe.Gaming.WalletConnect.Models;
using ChainSafe.Gaming.WalletConnect.Storage;
using ChainSafe.Gaming.WalletConnect.Wallets;
using ChainSafe.Gaming.Web3;
using ChainSafe.Gaming.Web3.Core;
using ChainSafe.Gaming.Web3.Core.Debug;
using ChainSafe.Gaming.Web3.Environment;
using ChainSafe.Gaming.Web3.Evm.Wallet;
using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.JsonRpc.Client.RpcMessages;
using Newtonsoft.Json;
using Org.BouncyCastle.Math;
using WalletConnectSharp.Common.Logging;
using WalletConnectSharp.Common.Model.Errors;
using WalletConnectSharp.Common.Utils;
using WalletConnectSharp.Core;
using WalletConnectSharp.Core.Models;
using WalletConnectSharp.Core.Models.Publisher;
using WalletConnectSharp.Network.Models;
using WalletConnectSharp.Sign;
using WalletConnectSharp.Sign.Models;
using WalletConnectSharp.Sign.Models.Engine;
using BigInteger = System.Numerics.BigInteger;
namespace ChainSafe.Gaming.WalletConnect
{
/// <summary>
/// Default implementation of <see cref="IWalletProvider"/>.
/// </summary>
public class WalletConnectProvider : WalletProvider, ILifecycleParticipant, IConnectionHelper
{
private readonly ILogWriter logWriter;
private readonly IWalletConnectConfig config;
private readonly DataStorage storage;
private readonly IChainConfig chainConfig;
private readonly IOperatingSystemMediator osMediator;
private readonly IWalletRegistry walletRegistry;
private readonly RedirectionHandler redirection;
private readonly IHttpClient httpClient;
private WalletConnectCore core;
private WalletConnectSignClient signClient;
private RequiredNamespaces requiredNamespaces;
private LocalData localData;
private SessionStruct session;
private bool connected;
private bool initialized;
private ConnectionHandlerConfig connectionHandlerConfig;
public WalletConnectProvider(
IWalletConnectConfig config,
DataStorage storage,
IChainConfig chainConfig,
IWalletRegistry walletRegistry,
RedirectionHandler redirection,
Web3Environment environment)
: base(environment, chainConfig)
{
this.redirection = redirection;
this.walletRegistry = walletRegistry;
osMediator = environment.OperatingSystem;
this.chainConfig = chainConfig;
this.storage = storage;
this.config = config;
logWriter = environment.LogWriter;
httpClient = environment.HttpClient;
}
public bool StoredSessionAvailable => localData.SessionTopic != null;
private bool OsManageWalletSelection => osMediator.Platform == Platform.Android;
private static bool SessionExpired(SessionStruct s) => s.Expiry != null && Clock.IsExpired((long)s.Expiry);
public async ValueTask WillStartAsync()
{
await Initialize();
}
private async Task Initialize()
{
if (initialized)
{
return;
}
ValidateConfig();
WCLogger.Logger = new WCLogWriter(logWriter, config);
localData = !config.ForceNewSession
? await storage.LoadLocalData() ?? new LocalData()
: new LocalData();
core = new WalletConnectCore(new CoreOptions
{
Name = config.ProjectName,
ProjectId = config.ProjectId,
Storage = storage.BuildStorage(sessionStored: !string.IsNullOrEmpty(localData.SessionTopic)),
BaseContext = config.BaseContext,
ConnectionBuilder = config.ConnectionBuilder,
});
await core.Start();
signClient = await WalletConnectSignClient.Init(new SignClientOptions
{
BaseContext = config.BaseContext,
Core = core,
Metadata = config.Metadata,
Name = config.ProjectName,
ProjectId = config.ProjectId,
Storage = core.Storage,
});
requiredNamespaces = new RequiredNamespaces
{
{
ChainModel.EvmNamespace,
new ProposedNamespace
{
Chains = new[] { $"{ChainModel.EvmNamespace}:{chainConfig.ChainId}", },
Events = new[] { "chainChanged", "accountsChanged" },
Methods = new[]
{
"eth_sign",
"personal_sign",
"eth_signTypedData",
"eth_signTransaction",
"eth_sendTransaction",
"eth_getTransactionByHash",
"wallet_switchEthereumChain",
"eth_blockNumber",
},
}
},
};
initialized = true;
}
private void ValidateConfig()
{
if (string.IsNullOrWhiteSpace(config.ProjectId))
{
throw new WalletConnectException("ProjectId was not set.");
}
if (string.IsNullOrWhiteSpace(config.StoragePath))
{
throw new WalletConnectException("Storage folder path was not set.");
}
}
public ValueTask WillStopAsync()
{
signClient?.Dispose();
core?.Dispose();
return new ValueTask(Task.CompletedTask);
}
public override async Task<string> Connect()
{
if (connected)
{
throw new WalletConnectException(
$"Tried connecting {nameof(WalletConnectProvider)}, but it's already been connected.");
}
if (!initialized)
{
await Initialize();
}
try
{
var sessionStored = !string.IsNullOrEmpty(localData.SessionTopic);
session = !sessionStored
? await ConnectSession()
: await RestoreSession();
localData.SessionTopic = session.Topic;
var sessionLocalWallet = GetSessionLocalWallet();
if (sessionLocalWallet != null)
{
localData.ConnectedLocalWalletName = sessionLocalWallet.Name;
WCLogger.Log($"\"{sessionLocalWallet.Name}\" set as locally connected wallet for the current session.");
}
else
{
localData.ConnectedLocalWalletName = null;
WCLogger.Log("Remote wallet connected.");
}
if (config.RememberSession)
{
await storage.SaveLocalData(localData);
}
else
{
storage.ClearLocalData();
}
var address = GetPlayerAddress();
if (!AddressExtensions.IsPublicAddress(address))
{
throw new Web3Exception("Public address provided by WalletConnect is not valid.");
}
connected = true;
await CheckAndSwitchNetwork();
return address;
}
catch (Exception e)
{
storage.ClearLocalData();
throw new WalletConnectException("Error occured during WalletConnect connection process.", e);
}
}
private async Task CheckAndSwitchNetwork()
{
var chainId = GetChainId();
if (chainId != $"{ChainModel.EvmNamespace}:{chainConfig.ChainId}")
{
await SwitchChain(chainConfig.ChainId);
UpdateSessionChainId();
}
}
private void UpdateSessionChainId()
{
var defaultChain = session.Namespaces.Keys.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(defaultChain))
{
var defaultNamespace = session.Namespaces[defaultChain];
var chains = ConvertArrayToListAndRemoveFirst(defaultNamespace.Chains);
defaultNamespace.Chains = chains.ToArray();
var accounts = ConvertArrayToListAndRemoveFirst(defaultNamespace.Accounts);
defaultNamespace.Accounts = accounts.ToArray();
}
else
{
throw new Web3Exception("Can't update session chain ID. Default chain not found.");
}
}
private List<T> ConvertArrayToListAndRemoveFirst<T>(T[] array)
{
var list = array.ToList();
list.RemoveAt(0);
return list;
}
public override async Task Disconnect()
{
if (!connected)
{
return;
}
WCLogger.Log("Disconnecting Wallet Connect session...");
try
{
storage.ClearLocalData();
localData = new LocalData();
await signClient.Disconnect(session.Topic, Error.FromErrorType(ErrorType.USER_DISCONNECTED));
await core.Storage.Clear();
connected = false;
}
catch (Exception e)
{
WCLogger.LogError($"Error occured during disconnect: {e}");
}
}
private async Task<SessionStruct> ConnectSession()
{
if (config.ConnectionHandlerProvider == null)
{
throw new WalletConnectException($"Can not connect to a new session. No {nameof(IConnectionHandlerProvider)} was set in config.");
}
var connectOptions = new ConnectOptions { RequiredNamespaces = requiredNamespaces };
var connectedData = await signClient.Connect(connectOptions);
var connectionHandler = await config.ConnectionHandlerProvider.ProvideHandler();
Task dialogTask;
try
{
connectionHandlerConfig = new ConnectionHandlerConfig
{
ConnectRemoteWalletUri = connectedData.Uri,
DelegateLocalWalletSelectionToOs = OsManageWalletSelection,
WalletLocationOption = config.WalletLocationOption,
LocalWalletOptions = !OsManageWalletSelection
? walletRegistry.EnumerateSupportedWallets(osMediator.Platform)
.ToList() // todo notify devs that some wallets don't work on Desktop
: null,
RedirectToWallet = !OsManageWalletSelection
? walletName => redirection.RedirectConnection(connectedData.Uri, walletName)
: null,
RedirectOsManaged = OsManageWalletSelection
? () => redirection.RedirectConnectionOsManaged(connectedData.Uri)
: null,
};
dialogTask = connectionHandler.ConnectUserWallet(connectionHandlerConfig);
// awaiting handler task to catch exceptions, actually awaiting only for approval
var combinedTasks = await Task.WhenAny(dialogTask, connectedData.Approval);
if (combinedTasks.IsFaulted)
{
await combinedTasks; // this will throw the exception
}
}
finally
{
try
{
connectionHandler.Terminate();
}
catch
{
// ignored
}
}
var newSession = await connectedData.Approval;
WCLogger.Log("Wallet connected using new session.");
return newSession;
}
private async Task<SessionStruct> RestoreSession()
{
var storedSession = signClient.Find(requiredNamespaces).First(s => s.Topic == localData.SessionTopic);
if (SessionExpired(storedSession))
{
await RenewSession();
}
WCLogger.Log("Wallet connected using stored session.");
return storedSession;
}
private async Task RenewSession()
{
try
{
var acknowledgement = await signClient.Extend(session.Topic);
TryRedirectToWallet();
await acknowledgement.Acknowledged();
}
catch (Exception e)
{
throw new WalletConnectException("Auto-renew session failed.", e);
}
WCLogger.Log("Renewed session successfully.");
}
public override async Task<T> Request<T>(string method, params object[] parameters)
{
if (!connected)
{
throw new WalletConnectException("Can't send requests. No session is connected at the moment.");
}
if (SessionExpired(session))
{
if (config.AutoRenewSession)
{
await RenewSession();
}
else
{
throw new WalletConnectException(
$"Failed to perform {typeof(T)} request - session expired. Please reconnect.");
}
}
var sessionTopic = session.Topic;
EventUtils.ListenOnce<PublishParams>(
OnPublishedMessage,
handler => core.Relayer.Publisher.OnPublishedMessage += handler,
handler => core.Relayer.Publisher.OnPublishedMessage -= handler);
var chainId = GetChainId();
return await WalletConnectRequest<T>(sessionTopic, method, chainId, parameters);
void OnPublishedMessage(object sender, PublishParams args)
{
if (args.Topic != sessionTopic)
{
logWriter.LogError("Session topic is different than args -> " +
$"sessionTopic: {sessionTopic}, args.Topic: {args.Topic}");
return;
}
if (localData.ConnectedLocalWalletName != null)
{
redirection.Redirect(localData.ConnectedLocalWalletName);
}
}
}
private WalletModel GetSessionLocalWallet()
{
var nativeUrl = RemoveSlash(session.Peer.Metadata.Url);
var sessionWallet = walletRegistry
.EnumerateSupportedWallets(osMediator.Platform)
.FirstOrDefault(w => RemoveSlash(w.Homepage) == nativeUrl);
return sessionWallet;
string RemoveSlash(string s)
{
return s.EndsWith('/')
? s[..s.LastIndexOf('/')]
: s;
}
}
private void TryRedirectToWallet()
{
if (localData.ConnectedLocalWalletName == null)
{
return;
}
var sessionLocalWallet = GetSessionLocalWallet();
redirection.Redirect(sessionLocalWallet);
}
private string GetPlayerAddress()
{
return GetFullAddress().Split(":")[2];
}
private string GetChainId()
{
return string.Join(":", GetFullAddress().Split(":").Take(2));
}
private string GetFullAddress()
{
var defaultChain = session.Namespaces.Keys.FirstOrDefault();
if (string.IsNullOrWhiteSpace(defaultChain))
{
throw new Web3Exception("Can't get full address. Default chain not found.");
}
var defaultNamespace = session.Namespaces[defaultChain];
if (defaultNamespace.Accounts.Length == 0)
{
throw new Web3Exception("Can't get full address. No connected accounts.");
}
return defaultNamespace.Accounts[0];
}
private async Task<T> WalletConnectRequest<T>(string topic, string method, string chainId, params object[] parameters)
{
// Helper method to make a request using WalletConnectSignClient.
async Task<T> MakeRequest<TRequest>()
{
var data = (TRequest)Activator.CreateInstance(typeof(TRequest), parameters);
return await signClient.Request<TRequest, T>(topic, data, chainId);
}
switch (method)
{
case "personal_sign":
return await MakeRequest<EthSignMessage>();
case "eth_signTypedData":
return await MakeRequest<EthSignTypedData>();
case "eth_signTransaction":
return await MakeRequest<EthSignTransaction>();
case "eth_sendTransaction":
return await MakeRequest<EthSendTransaction>();
case "wallet_switchEthereumChain":
return await MakeRequest<WalletSwitchEthereumChain>();
default:
try
{
// Direct RPC request via http, WalletConnect RPC url.
string chain = session.Namespaces.First().Value.Chains[0];
// Using WalletConnect Blockchain API: https://docs.walletconnect.com/cloud/blockchain-api
var url = $"https://rpc.walletconnect.com/v1?chainId={chain}&projectId={config.ProjectId}";
string body = JsonConvert.SerializeObject(new RpcRequestMessage(Guid.NewGuid().ToString(), method, parameters));
var rawResult = await httpClient.PostRaw(url, body, "application/json");
RpcResponseMessage response = JsonConvert.DeserializeObject<RpcResponseMessage>(rawResult.Response);
return response.Result.ToObject<T>();
}
catch (Exception e)
{
throw new WalletConnectException($"{method} RPC method currently not implemented.", e);
}
}
}
}
}