-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathReownProvider.cs
More file actions
592 lines (500 loc) · 21.3 KB
/
ReownProvider.cs
File metadata and controls
592 lines (500 loc) · 21.3 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
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using ChainSafe.Gaming.Evm.Network;
using ChainSafe.Gaming.Evm.Providers;
using ChainSafe.Gaming.Reown.Connection;
using ChainSafe.Gaming.Reown.Methods;
using ChainSafe.Gaming.Reown.Models;
using ChainSafe.Gaming.Reown.Storage;
using ChainSafe.Gaming.Reown.Wallets;
using ChainSafe.Gaming.Web3;
using ChainSafe.Gaming.Web3.Analytics;
using ChainSafe.Gaming.Web3.Core;
using ChainSafe.Gaming.Web3.Core.Chains;
using ChainSafe.Gaming.Web3.Core.Debug;
using ChainSafe.Gaming.Web3.Core.Operations;
using ChainSafe.Gaming.Web3.Environment;
using ChainSafe.Gaming.Web3.Evm.Wallet;
using Nethereum.Hex.HexTypes;
using Nethereum.JsonRpc.Client.RpcMessages;
using Newtonsoft.Json;
using Reown.Core.Common.Logging;
using Reown.Core.Common.Model.Errors;
using Reown.Core.Common.Utils;
using Reown.Core.Crypto;
using Reown.Core.Models.Publisher;
using Reown.Core.Network.Models;
using Reown.Sign;
using Reown.Sign.Models;
using Reown.Sign.Models.Engine;
namespace ChainSafe.Gaming.Reown
{
/// <summary>
/// Reown implementation of <see cref="IWalletProvider"/>.
/// </summary>
public class ReownProvider : WalletProvider, ILifecycleParticipant, IConnectionHelper
{
private const string EvmNamespace = "eip155";
private readonly ILogWriter logWriter;
private readonly IReownConfig config;
private readonly IChainConfig chainConfig;
private readonly IOperatingSystemMediator osMediator;
private readonly IWalletRegistry walletRegistry;
private readonly RedirectionHandler redirection;
private readonly ReownHttpClient reownHttpClient;
private readonly IAnalyticsClient analyticsClient;
private readonly Web3Environment environment;
private readonly IChainConfigSet chainConfigSet;
private readonly IOperationTracker operationTracker;
private readonly IRpcProvider rpcProvider;
private Session session;
private bool connected;
private bool initialized;
private ConnectionHandlerConfig connectionHandlerConfig;
private Dictionary<string, ProposedNamespace> optionalNamespaces;
private WalletModel sessionWallet;
public ReownProvider(
IReownConfig config,
IChainConfig chainConfig,
IChainConfigSet chainConfigSet,
IWalletRegistry walletRegistry,
RedirectionHandler redirection,
Web3Environment environment,
ReownHttpClient reownHttpClient,
IOperationTracker operationTracker,
IRpcProvider rpcProvider,
IOperatingSystemMediator operatingSystemMediator)
: base(environment, chainConfig, operationTracker, operatingSystemMediator)
{
this.operationTracker = operationTracker;
this.rpcProvider = rpcProvider;
this.chainConfigSet = chainConfigSet;
this.environment = environment;
analyticsClient = environment.AnalyticsClient;
this.redirection = redirection;
this.walletRegistry = walletRegistry;
osMediator = environment.OperatingSystem;
this.chainConfig = chainConfig;
this.config = config;
logWriter = environment.LogWriter;
this.reownHttpClient = reownHttpClient;
}
public SignClient SignClient { get; private set; }
public bool StoredSessionAvailable
{
get
{
if (!SignClient.AddressProvider.HasDefaultSession)
{
return false; // no session stored
}
if (string.IsNullOrWhiteSpace(SignClient.AddressProvider.DefaultSession.Topic))
{
return false; // session topic is empty
}
if (!SignClient.Session.Keys.Contains(SignClient.AddressProvider.DefaultSession.Topic))
{
return false; // usually happens when session was closed on the wallet side
}
return true;
}
}
private bool OsManageWalletSelection => osMediator.Platform == Platform.Android;
private static bool SessionExpired(Session s) => s.Expiry != null && Clock.IsExpired((long)s.Expiry);
public async ValueTask WillStartAsync()
{
await Initialize();
}
private async Task Initialize()
{
if (initialized)
{
return;
}
analyticsClient.CaptureEvent(new AnalyticsEvent()
{
EventName = "Reown Initialized",
PackageName = "io.chainsafe.web3-unity",
});
config.Validate();
ReownLogger.Instance = new ReownLogWriter(logWriter, config);
var storage = await ReownStorageFactory.Build(environment);
var signClientOptions = new SignClientOptions
{
ProjectId = config.ProjectId,
Name = config.ProjectName,
Metadata = config.Metadata,
BaseContext = config.BaseContext,
Storage = storage,
KeyChain = new KeyChain(storage),
ConnectionBuilder = config.ConnectionBuilder,
RelayUrlBuilder = config.RelayUrlBuilder,
};
SignClient = await SignClient.Init(signClientOptions);
await SignClient.AddressProvider.LoadDefaultsAsync();
if (config.OnRelayErrored is not null)
{
SignClient.CoreClient.Relayer.OnErrored += config.OnRelayErrored;
}
var optionalNamespace =
new ProposedNamespace // todo using optional namespaces like AppKit does, should they be required?
{
Chains = chainConfigSet.Configs
.Select(chainEntry => chainEntry.ChainId)
.ToArray(),
Methods = new[]
{
"eth_sign",
"personal_sign",
"eth_signTypedData",
"eth_signTransaction",
"eth_sendTransaction",
"eth_chainId",
"eth_getTransactionByHash",
"wallet_switchEthereumChain",
"wallet_addEthereumChain",
"eth_blockNumber",
},
Events = new[]
{
"chainChanged",
"accountsChanged",
},
};
optionalNamespaces = new Dictionary<string, ProposedNamespace>
{
{ EvmNamespace, optionalNamespace },
};
initialized = true;
}
protected override Task<string> GetWalletChainId()
{
var chain = session.Namespaces.First().Value.Chains[0].Split(":");
return Task.FromResult(chain[^1]);
}
public ValueTask WillStopAsync()
{
SignClient?.Dispose();
return new ValueTask(Task.CompletedTask);
}
public override async Task<string> Connect()
{
if (connected)
{
throw new ReownIntegrationException(
$"Tried connecting with {nameof(ReownProvider)}, but was already connected.");
}
if (!initialized)
{
await Initialize();
}
try
{
session = !config.RememberSession || !StoredSessionAvailable
? await ConnectSession()
: await RestoreSession();
var address = GetPlayerAddress();
if (!AddressExtensions.IsPublicAddress(address))
{
throw new ReownIntegrationException("Public address provided by Reown is not valid.");
}
sessionWallet = GetSessionWallet();
if (sessionWallet is null)
{
ReownLogger.Log("Couldn't identify the wallet used to connect the session. " +
"Redirection is disabled. " +
$"URL from wallet metadata is \"{session.Peer.Metadata.Url}\".");
}
connected = true;
await SwitchChainAddIfMissing();
return address;
}
catch (Exception e)
{
SignClient.AddressProvider.DefaultSession = default; // reset saved session
await SignClient.CoreClient.Storage.Clear();
throw new ReownIntegrationException("Error occured during Reown connection process.", e);
}
}
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 string BuildChainIdForReown(string chainId)
{
return $"{EvmNamespace}:{chainId}";
}
private List<T> ConvertArrayToListAndRemoveFirst<T>(T[] array)
{
var list = array.ToList();
list.RemoveAt(0);
return list;
}
public override async Task Disconnect()
{
if (!connected)
{
return;
}
ReownLogger.Log("Disconnecting Reown session...");
try
{
await SignClient.Disconnect(session.Topic, Error.FromErrorType(ErrorType.USER_DISCONNECTED));
await SignClient.CoreClient.Storage.Clear();
connected = false;
}
catch (Exception e)
{
ReownLogger.LogError($"Error occured during disconnect: {e}");
}
}
private async Task<Session> ConnectSession()
{
ConnectedData connectedData;
IConnectionHandler connectionHandler;
var connectOptions = new ConnectOptions { OptionalNamespaces = optionalNamespaces };
connectedData = await SignClient.Connect(connectOptions);
connectionHandler = await config.ConnectionHandlerProvider.ProvideHandler();
try
{
connectionHandlerConfig = new ConnectionHandlerConfig
{
ConnectRemoteWalletUri = connectedData.Uri,
DelegateLocalWalletSelectionToOs = OsManageWalletSelection,
WalletLocationOption = config.WalletLocationOption,
LocalWalletOptions = !OsManageWalletSelection
? walletRegistry.SupportedWallets.ToList()
: null,
HttpHeaders = reownHttpClient.BuildHeaders(),
WalletIconEndpoint = $"{ReownHttpClient.Host}/getWalletImage/",
RedirectToWallet = !OsManageWalletSelection
? OnRedirectToWallet
: null,
RedirectOsManaged = OsManageWalletSelection
? () => redirection.RedirectConnectionOsManaged(connectedData.Uri)
: null,
};
void OnRedirectToWallet(string walletId)
{
SignClient.CoreClient.Storage.SetItem("ChainSafe_RecentLocalWalletId", walletId); // saving wallet id to enable future redirection
redirection.RedirectConnection(connectedData.Uri, walletId);
}
var 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;
ReownLogger.Log("Wallet connected using new session.");
return newSession;
}
private async Task<Session> RestoreSession()
{
session = SignClient.AddressProvider.DefaultSession;
if (SessionExpired(session))
{
await RenewSession();
}
ReownLogger.Log("Wallet connected using stored session.");
return session;
}
private async Task RenewSession()
{
using (operationTracker.TrackOperation("Renewing the Reown session..."))
{
try
{
var acknowledgement = await SignClient.Extend(session.Topic);
TryRedirectToWallet();
await acknowledgement.Acknowledged();
}
catch (Exception e)
{
throw new ReownIntegrationException("Session renewal failed.", e);
}
}
ReownLogger.Log("Renewed session successfully.");
}
public override async Task<T> Request<T>(string method, params object[] parameters)
{
if (!connected)
{
throw new ReownIntegrationException("Can't send requests. No session is connected at the moment.");
}
if (SessionExpired(session))
{
if (config.AutoRenewSession)
{
await RenewSession();
}
else
{
throw new ReownIntegrationException(
$"Failed to perform {typeof(T)} request - session expired. Please reconnect.");
}
}
var sessionTopic = session.Topic;
EventUtils.ListenOnce<PublishParams>(
OnPublishedMessage,
handler => SignClient.CoreClient.Relayer.Publisher.OnPublishedMessage += handler,
handler => SignClient.CoreClient.Relayer.Publisher.OnPublishedMessage -= handler);
// For whatever reason, android and iOS are forcefully killing our thread where this is being run on
// So we are ensuring that the request survives the thread kill by running it on the main thread
return
osMediator.Platform is Platform.Android or Platform.IOS ?
await Task.Run(() => ReownRequest<T>(sessionTopic, method, parameters))
: await ReownRequest<T>(sessionTopic, method, 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;
}
logWriter.Log("This is message:\n" + args.Message);
TryRedirectToWallet();
}
}
private WalletModel GetSessionWallet()
{
var nativeUrl = RemoveSlash(session.Peer.Metadata.Url);
var wallet = walletRegistry
.SupportedWallets
.FirstOrDefault(w => RemoveSlash(w.Homepage) == nativeUrl);
return wallet;
string RemoveSlash(string s)
{
return s.EndsWith('/')
? s[..s.LastIndexOf('/')]
: s;
}
}
private async void TryRedirectToWallet()
{
if (sessionWallet is null)
{
logWriter.Log("Session wallet couldn't be determined. No redirection is going to happen.");
return; // session wallet couldn't be determined, ignore redirection
}
if (!await SignClient.CoreClient.Storage.HasItem("ChainSafe_RecentLocalWalletId"))
{
logWriter.Log("No local wallets connected. No redirection is going to happen.");
return; // no local wallets connected - ignore redirection
}
var recentLocalWalletId = await SignClient.CoreClient.Storage.GetItem<string>("ChainSafe_RecentLocalWalletId");
if (recentLocalWalletId != sessionWallet.Id)
{
ReownLogger.Log("Last clicked local wallet was not used to connect the session. " +
"Assuming the wallet was connected remotely. No redirection is going to happen.");
return;
}
redirection.Redirect(sessionWallet); // safe to redirect
}
private string GetPlayerAddress()
{
return GetFullAddress().Split(":")[2];
}
private string ExtractChainIdFromAddress()
{
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> ReownRequest<T>(string topic, string method, params object[] parameters)
{
// Helper method to make a request using ReownSignClient.
async Task<T> MakeRequest<TRequest>(bool sendChainId = true)
{
var data = (TRequest)Activator.CreateInstance(typeof(TRequest), parameters);
try
{
return await SignClient.Request<TRequest, T>(
topic,
data,
sendChainId ? BuildChainIdForReown(chainConfig.ChainId) : null);
}
catch (KeyNotFoundException e)
{
throw new ReownIntegrationException("Can't execute request. The session was most likely terminated on the wallet side.", e);
}
}
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>(false);
case "wallet_addEthereumChain":
return await MakeRequest<WalletAddEthereumChain>(false);
case "eth_chainId":
return await MakeRequest<WalletGetChainId>();
default:
try
{
// Direct RPC request via http, Reown RPC url.
var chain = session.Namespaces.First().Value.Chains[0];
// Using Reown Blockchain API: https://docs.reown.com/cloud/blockchain-api
var url = $"https://rpc.walletconnect.com/v1?chainId={chain}&projectId={config.ProjectId}";
var body = JsonConvert.SerializeObject(new RpcRequestMessage(Guid.NewGuid().ToString(), method, parameters));
var rawResult = await reownHttpClient.PostRaw(url, body, "application/json");
var response = JsonConvert.DeserializeObject<RpcResponseMessage>(rawResult.Response);
return response.Result.ToObject<T>();
}
catch (Exception e)
{
throw new ReownIntegrationException($"{method} RPC method currently not implemented.", e);
}
}
}
}
}