From ea790be2f342e92764afb553bbcc3236f81990e6 Mon Sep 17 00:00:00 2001 From: rob1997 Date: Thu, 4 Jul 2024 16:50:26 +0300 Subject: [PATCH 1/9] checkpoint, IWalletProvider abstracted for web3auth but only signing working --- .../Runtime/Scripts/HyperPlayWebGLProvider.cs | 8 +- .../Runtime/IWeb3AuthTransactionHandler.cs | 4 - .../Scripts/Web3AuthWalletGUIUIManager.cs | 6 +- .../Runtime/Web3AuthProvider.cs | 93 ++++++++ ...allet.cs.meta => Web3AuthProvider.cs.meta} | 2 +- .../Runtime/Web3AuthSigner.cs | 31 +++ .../Runtime/Web3AuthSigner.cs.meta | 11 + .../Runtime/Web3AuthTransactionExecutor.cs | 66 ++++++ .../Web3AuthTransactionExecutor.cs.meta | 11 + .../Runtime/Web3AuthTransactionHandler.cs | 36 ---- .../Web3AuthTransactionHandler.cs.meta | 3 - .../Runtime/Web3AuthWallet.cs | 200 ------------------ .../Runtime/Web3AuthWalletExtensions.cs | 13 +- .../Runtime/StubWalletConnectProvider.cs | 31 ++- .../HyperPlayProvider.cs | 16 +- .../AccountProvider.cs | 14 ++ .../InProcessSigner.cs | 53 +++-- .../InProcessTransactionExecutor.cs | 48 ++--- .../MetaMaskProvider.cs | 17 +- .../WalletConnectProvider.cs | 48 ++--- .../Web3/Core/Environment/Web3Environment.cs | 1 + .../Web3/Evm/JsonRpc/RpcClientConfig.cs | 13 -- .../Web3/Evm/JsonRpc/RpcClientExtensions.cs | 24 --- .../Web3/Evm/JsonRpc/RpcClientProvider.cs | 46 ++-- .../Web3/Evm/Wallet/IWalletProvider.cs | 2 + .../Web3/Evm/Wallet/WalletProvider.cs | 33 +-- .../Web3/Evm/Wallet/WalletSigner.cs | 4 +- .../Evm/Wallet/WalletTransactionExecutor.cs | 2 +- 28 files changed, 362 insertions(+), 474 deletions(-) create mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs rename Packages/io.chainsafe.web3-unity.web3auth/Runtime/{Web3AuthWallet.cs.meta => Web3AuthProvider.cs.meta} (83%) create mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs create mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs.meta create mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs create mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs.meta delete mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionHandler.cs delete mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionHandler.cs.meta delete mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWallet.cs create mode 100644 src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs delete mode 100644 src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientConfig.cs diff --git a/Packages/io.chainsafe.web3-unity.hyperplay/Runtime/Scripts/HyperPlayWebGLProvider.cs b/Packages/io.chainsafe.web3-unity.hyperplay/Runtime/Scripts/HyperPlayWebGLProvider.cs index 8e2ed3ed7..a536e9647 100644 --- a/Packages/io.chainsafe.web3-unity.hyperplay/Runtime/Scripts/HyperPlayWebGLProvider.cs +++ b/Packages/io.chainsafe.web3-unity.hyperplay/Runtime/Scripts/HyperPlayWebGLProvider.cs @@ -17,6 +17,7 @@ public class HyperPlayWebGLProvider : HyperPlayProvider private readonly IHyperPlayConfig _config; private readonly IHyperPlayData _data; private readonly DataStorage _dataStorage; + private readonly IHttpClient _httpClient; private readonly IChainConfig _chainConfig; private readonly ChainRegistryProvider _chainRegistryProvider; private readonly EthereumWindowController _ethereumController; @@ -27,14 +28,15 @@ public class HyperPlayWebGLProvider : HyperPlayProvider /// Injected . /// Injected . /// Injected . - /// HttpClient to make requests. + /// Injected . /// ChainConfig to fetch chain data. /// Injected . - public HyperPlayWebGLProvider(IHyperPlayConfig config, IHyperPlayData data, DataStorage dataStorage, IHttpClient httpClient, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) : base(config, data, dataStorage, httpClient, chainConfig, chainRegistryProvider) + public HyperPlayWebGLProvider(IHyperPlayConfig config, IHyperPlayData data, DataStorage dataStorage, Web3Environment environment, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) : base(config, data, dataStorage, environment, chainConfig, chainRegistryProvider) { _config = config; _data = data; _dataStorage = dataStorage; + _httpClient = environment.HttpClient; _chainConfig = chainConfig; _chainRegistryProvider = chainRegistryProvider; @@ -84,7 +86,7 @@ public override async Task Connect() /// RPC request parameters. /// RPC request response type. /// RPC request Response. - public override async Task Perform(string method, params object[] parameters) + public override async Task Request(string method, params object[] parameters) { var response = await _ethereumController.Request(method, parameters); diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs index 38d9460a1..1e5cfd705 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs @@ -9,10 +9,6 @@ public interface IWeb3AuthTransactionHandler public event Action OnTransactionConfirmed; - public event Action OnTransactionApproved; - - public event Action OnTransactionDeclined; - public void RequestTransaction(TransactionRequested transactionRequested); public void ConfirmTransaction(TransactionConfirmed transactionConfirmed); diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs index a55a30dab..7e00814c2 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using ChainSafe.Gaming.InProcessSigner; using ChainSafe.Gaming.UnityPackage; using ChainSafe.GamingSdk.Web3Auth; using TMPro; @@ -184,8 +185,9 @@ private IEnumerator CheckHoldPrivateKeyButtonInput() /// private void SetPrivateKey() { - var web3AuthWallet = (Web3AuthWallet)Web3Accessor.Web3.ServiceProvider.GetService(typeof(Web3AuthWallet)); - privateKeyText.text = web3AuthWallet.Key; + var accountProvider = (AccountProvider)Web3Accessor.Web3.ServiceProvider.GetService(typeof(AccountProvider)); + + privateKeyText.text = accountProvider.Account.PrivateKey; } /// diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs new file mode 100644 index 000000000..ce8b9fafe --- /dev/null +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs @@ -0,0 +1,93 @@ +using System.Threading.Tasks; +using ChainSafe.Gaming.Evm; +using ChainSafe.Gaming.InProcessSigner; +using ChainSafe.Gaming.Web3; +using ChainSafe.Gaming.Web3.Environment; +using ChainSafe.Gaming.Web3.Evm.Wallet; +using ChainSafe.GamingSdk.Web3Auth; +using Nethereum.Web3.Accounts; +using UnityEngine; + +public class Web3AuthProvider : WalletProvider +{ + private readonly Web3AuthWalletConfig _config; + private readonly AccountProvider _accountProvider; + + private Web3Auth _coreInstance; + private TaskCompletionSource _connectTcs; + private TaskCompletionSource _disconnectTcs; + + public Web3AuthProvider(Web3AuthWalletConfig config, AccountProvider accountProvider, Web3Environment environment, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) : base(environment, chainRegistryProvider, chainConfig) + { + _config = config; + _accountProvider = accountProvider; + } + + public override async Task Connect() + { + _coreInstance = Object.FindObjectOfType(); + + if (_coreInstance == null) + { + var gameObject = new GameObject("Web3Auth", typeof(Web3Auth)); + + Object.DontDestroyOnLoad(gameObject); + + _coreInstance = gameObject.GetComponent(); + } + + _coreInstance.setOptions(_config.Web3AuthOptions, _config.RememberMe); + + if (_connectTcs != null && !_connectTcs.Task.IsCompleted) + { + _connectTcs.SetCanceled(); + } + + _connectTcs = new TaskCompletionSource(); + + _coreInstance.onLogin += OnLogin; + + _coreInstance.login(_config.LoginParams); + + var response = await _connectTcs.Task; + + var account = new Account(response.privKey); + + _accountProvider.Initialize(account); + + return account.Address; + } + + private void OnLogin(Web3AuthResponse response) + { + _connectTcs.SetResult(response); + } + + public override async Task Disconnect() + { + if (_disconnectTcs != null && !_disconnectTcs.Task.IsCompleted) + { + _disconnectTcs.SetCanceled(); + } + + _disconnectTcs = new TaskCompletionSource(); + + _coreInstance.onLogout += OnLogout; + + _coreInstance.logout(); + + await _disconnectTcs.Task; + + Object.Destroy(_coreInstance.gameObject); + + void OnLogout() + { + _disconnectTcs.SetResult(null); + } + } + + public override Task Request(string method, params object[] parameters) + { + return Perform(method, parameters); + } +} diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWallet.cs.meta b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs.meta similarity index 83% rename from Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWallet.cs.meta rename to Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs.meta index 9484771f1..af6a84079 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWallet.cs.meta +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c38937061ec1df74c8ce8dc1898238c2 +guid: 315f561b26677c24588d042c02411964 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs new file mode 100644 index 000000000..dffea3f0e --- /dev/null +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs @@ -0,0 +1,31 @@ +using System.Threading.Tasks; +using ChainSafe.Gaming.InProcessSigner; +using ChainSafe.Gaming.Web3.Core; +using ChainSafe.Gaming.Web3.Core.Logout; +using ChainSafe.Gaming.Web3.Evm.Wallet; +using UnityEngine; + +public class Web3AuthSigner : InProcessSigner, ILifecycleParticipant, ILogoutHandler +{ + private readonly IWalletProvider _walletProvider; + + public Web3AuthSigner(AccountProvider accountProvider, IWalletProvider walletProvider) : base(accountProvider) + { + _walletProvider = walletProvider; + } + + public async ValueTask WillStartAsync() + { + await _walletProvider.Connect(); + } + + public virtual ValueTask WillStopAsync() + { + return new ValueTask(Task.CompletedTask); + } + + public async Task OnLogout() + { + await _walletProvider.Disconnect(); + } +} diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs.meta b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs.meta new file mode 100644 index 000000000..0108a8fd8 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d19f6325a0df498499557519b5ef39a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs new file mode 100644 index 000000000..9ab2b83d0 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using ChainSafe.Gaming.Evm.Providers; +using ChainSafe.Gaming.Evm.Transactions; +using ChainSafe.Gaming.InProcessSigner; +using ChainSafe.Gaming.InProcessTransactionExecutor; +using ChainSafe.GamingSdk.Web3Auth; + +public class Web3AuthTransactionExecutor : InProcessTransactionExecutor, IWeb3AuthTransactionHandler +{ + public event Action OnTransactionRequested; + + public event Action OnTransactionConfirmed; + + private readonly Dictionary> _transactionPool = + new Dictionary>(); + + public Web3AuthTransactionExecutor(AccountProvider accountProvider, IRpcProvider rpcProvider) : base(accountProvider, rpcProvider) + { + } + + public override Task SendTransaction(TransactionRequest transaction) + { + string id = Guid.NewGuid().ToString(); + + var request = new TransactionRequested(id, transaction); + + var tcs = new TaskCompletionSource(); + + _transactionPool.Add(request, tcs); + + RequestTransaction(request); + + return tcs.Task; + } + + public void RequestTransaction(TransactionRequested transactionRequested) + { + OnTransactionRequested?.Invoke(transactionRequested); + } + + public void ConfirmTransaction(TransactionConfirmed transactionConfirmed) + { + OnTransactionConfirmed?.Invoke(transactionConfirmed); + } + + public async void ApproveTransaction(TransactionApproved transactionApproved) + { + var pair = _transactionPool.Single(t => t.Key.Id == transactionApproved.Id); + + var response = await base.SendTransaction(pair.Key.Transaction); + + pair.Value.SetResult(response); + + ConfirmTransaction(new TransactionConfirmed(response)); + } + + public void DeclineTransaction(TransactionDeclined transactionDeclined) + { + var pair = _transactionPool.Single(t => t.Key.Id == transactionDeclined.Id); + + pair.Value.SetCanceled(); + } +} diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs.meta b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs.meta new file mode 100644 index 000000000..88efcacc1 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0d28ef6f350480042b13aa99207a6401 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionHandler.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionHandler.cs deleted file mode 100644 index 58acfc6ee..000000000 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionHandler.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using ChainSafe.Gaming.Evm.Transactions; - -namespace ChainSafe.GamingSdk.Web3Auth -{ - public class Web3AuthTransactionHandler : IWeb3AuthTransactionHandler - { - public event Action OnTransactionRequested; - - public event Action OnTransactionConfirmed; - - public event Action OnTransactionApproved; - - public event Action OnTransactionDeclined; - - public void RequestTransaction(TransactionRequested transactionRequested) - { - OnTransactionRequested?.Invoke(transactionRequested); - } - - public void ConfirmTransaction(TransactionConfirmed transactionConfirmed) - { - OnTransactionConfirmed?.Invoke(transactionConfirmed); - } - - public void ApproveTransaction(TransactionApproved transactionApproved) - { - OnTransactionApproved?.Invoke(transactionApproved); - } - - public void DeclineTransaction(TransactionDeclined transactionDeclined) - { - OnTransactionDeclined?.Invoke(transactionDeclined); - } - } -} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionHandler.cs.meta b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionHandler.cs.meta deleted file mode 100644 index f0213295f..000000000 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionHandler.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 4e8795100f1f43cf9df164552a3fd166 -timeCreated: 1718955415 \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWallet.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWallet.cs deleted file mode 100644 index ac91c0d46..000000000 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWallet.cs +++ /dev/null @@ -1,200 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using ChainSafe.Gaming.Evm.Providers; -using ChainSafe.Gaming.Evm.Signers; -using ChainSafe.Gaming.Evm.Transactions; -using ChainSafe.Gaming.InProcessSigner; -using ChainSafe.Gaming.InProcessTransactionExecutor; -using ChainSafe.Gaming.Web3; -using ChainSafe.Gaming.Web3.Analytics; -using ChainSafe.Gaming.Web3.Core; -using ChainSafe.Gaming.Web3.Core.Evm; -using Nethereum.JsonRpc.Client; -using Nethereum.Signer; -using UnityEngine; -using Object = UnityEngine.Object; -using TWeb3Auth = Web3Auth; - -namespace ChainSafe.GamingSdk.Web3Auth -{ - /// - /// A class that represents a Web3Auth wallet and provides functionality for signing transactions and interacting with a blockchain. - /// - public class Web3AuthWallet : ISigner, ITransactionExecutor, ILifecycleParticipant - { - private readonly Web3AuthWalletConfig config; - private readonly IRpcProvider rpcProvider; - private TWeb3Auth coreInstance; - private InProcessSigner signer; - private InProcessTransactionExecutor transactionExecutor; - private IClient rpcClient; - private readonly IAnalyticsClient analyticsClient; - private readonly IWeb3AuthTransactionHandler transactionHandler; - - /// - /// Initializes a new instance of the class. - /// - /// The configuration for the Web3Auth wallet. - /// The RPC provider for blockchain interaction. - /// - /// - public Web3AuthWallet(Web3AuthWalletConfig config, IRpcProvider rpcProvider, IClient rpcClient, IWeb3AuthTransactionHandler transactionHandler, IAnalyticsClient analyticsClient) - { - this.config = config; - this.rpcProvider = rpcProvider; - this.rpcClient = rpcClient; - this.analyticsClient = analyticsClient; - - this.transactionHandler = transactionHandler; - } - - /// - /// Gets the blockchain address associated with this wallet. - /// - public string PublicAddress => signer.PublicAddress; - - /// - /// Gets key. - /// - public string Key => signer.GetKey().GetPrivateKey(); - - private readonly Dictionary> _transactionPool = - new Dictionary>(); - - /// - /// Asynchronously prepares the Web3Auth wallet for operation, triggered when initializing the module in the dependency injection work flow. - /// - /// A representing the asynchronous operation. - public async ValueTask WillStartAsync() - { - - analyticsClient.CaptureEvent(new AnalyticsEvent() - { - EventName = $"Web3Auth Initialized", - PackageName = "io.chainsafe.web3-unity.web3auth", - }); - coreInstance = CreateCoreInstance(); - TaskCompletionSource loginTcs = new(); - coreInstance.onLogin += Web3Auth_OnLogin; - - if (config.LoginParams != null) coreInstance.login(config.LoginParams); - - var privateKeyString = await loginTcs.Task; - var privateKey = new EthECKey(privateKeyString); - - var signerConfig = new InProcessSignerConfig { PrivateKey = privateKey }; - - signer = new InProcessSigner(signerConfig); - - - transactionExecutor = new InProcessTransactionExecutor(signer, analyticsClient.ChainConfig, rpcProvider, rpcClient); - - transactionHandler.OnTransactionApproved += OnTransactionApproved; - transactionHandler.OnTransactionDeclined += OnTransactionDeclined; - - void Web3Auth_OnLogin(Web3AuthResponse response) - { - coreInstance.onLogin -= Web3Auth_OnLogin; - loginTcs.SetResult(response.privKey); - } - } - - /// - /// Asynchronously cleans up the Web3Auth wallet and logs out. - /// - /// A representing the asynchronous operation. - public async ValueTask WillStopAsync() - { - TaskCompletionSource logoutTcs = new(); - coreInstance.onLogout += Web3Auth_OnLogout; - coreInstance.logout(); - - await logoutTcs.Task; - - coreInstance.onLogout -= Web3Auth_OnLogout; - - Object.Destroy(coreInstance.gameObject); - - transactionHandler.OnTransactionApproved += OnTransactionApproved; - transactionHandler.OnTransactionDeclined += OnTransactionDeclined; - - void Web3Auth_OnLogout() - { - logoutTcs.SetResult(null); - } - } - - /// - /// Signs a message using the private key associated with this wallet. - /// - /// The message to sign. - /// A that represents the asynchronous operation and returns the signature as a string. - public Task SignMessage(string message) => signer.SignMessage(message); - - /// - /// Signs an ERC2771 typed data request using the private key associated with this wallet. - /// - /// The type of the structured data to sign. - /// The domain information for the typed data. - /// The structured data to sign. - /// A that represents the asynchronous operation and returns the signature as a string. - public Task SignTypedData(SerializableDomain domain, TStructData message) => signer.SignTypedData(domain, message); - - /// - /// Sends a blockchain transaction using the private key associated with this wallet. - /// - /// The transaction request to send. - /// A that represents the asynchronous operation and returns a . - public Task SendTransaction(TransactionRequest transaction) - { - string id = Guid.NewGuid().ToString(); - - var request = new TransactionRequested(id, transaction); - - var tcs = new TaskCompletionSource(); - - _transactionPool.Add(request, tcs); - - transactionHandler.RequestTransaction(request); - - return tcs.Task; - } - - public async void OnTransactionApproved(TransactionApproved transactionApproved) - { - var pair = _transactionPool.Single(t => t.Key.Id == transactionApproved.Id); - - var response = await transactionExecutor.SendTransaction(pair.Key.Transaction); - - pair.Value.SetResult(response); - - transactionHandler.ConfirmTransaction(new TransactionConfirmed(response)); - - } - - public void OnTransactionDeclined(TransactionDeclined transactionDeclined) - { - var pair = _transactionPool.Single(t => t.Key.Id == transactionDeclined.Id); - - pair.Value.SetCanceled(); - } - - /// - /// Creates core instance. - /// - /// Core instance. - private TWeb3Auth CreateCoreInstance() - { - Debug.Log("Creating Core Instance"); - var gameObject = new GameObject("Web3Auth", typeof(TWeb3Auth)); - Object.DontDestroyOnLoad(gameObject); - - var instance = gameObject.GetComponent(); - instance.setOptions(config.Web3AuthOptions, config.RememberMe); - - return instance; - } - } -} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs index 492733d91..afd485548 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs @@ -1,7 +1,10 @@ using ChainSafe.Gaming.Evm.Signers; +using ChainSafe.Gaming.InProcessSigner; using ChainSafe.Gaming.Web3.Build; using ChainSafe.Gaming.Web3.Core; using ChainSafe.Gaming.Web3.Core.Evm; +using ChainSafe.Gaming.Web3.Core.Logout; +using ChainSafe.Gaming.Web3.Evm.Wallet; using ChainSafe.GamingSdk.Web3Auth; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -34,9 +37,13 @@ public static IWeb3ServiceCollection UseWeb3AuthWallet(this IWeb3ServiceCollecti collection.AssertServiceNotBound(); collection.AssertServiceNotBound(); - collection.AddSingleton(); - - collection.AddSingleton(); + collection.AddSingleton(); + + collection.Replace(ServiceDescriptor.Singleton(typeof(AccountProvider), new AccountProvider())); + + collection.AddSingleton(); + + collection.AddSingleton(); return collection; } diff --git a/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProvider.cs b/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProvider.cs index 658a83386..f400e5675 100644 --- a/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProvider.cs +++ b/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProvider.cs @@ -15,11 +15,11 @@ public class StubWalletConnectProvider : WalletProvider private readonly IChainConfig chainConfig; private readonly IHttpClient httpClient; - public StubWalletConnectProvider(StubWalletConnectProviderConfig config, IHttpClient httpClient, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) : base(chainRegistryProvider: chainRegistryProvider) + public StubWalletConnectProvider(StubWalletConnectProviderConfig config, Web3Environment environment, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) : base(environment, chainRegistryProvider, chainConfig) { this.config = config; this.chainConfig = chainConfig; - this.httpClient = httpClient; + httpClient = environment.HttpClient; } public override Task Connect() @@ -33,30 +33,25 @@ public override Task Disconnect() return Task.CompletedTask; } - public override Task Perform(string method, params object[] parameters) + public override async Task Request(string method, params object[] parameters) { switch (method) { - case "personal_sign": case "eth_signTypedData": case "eth_sendTransaction": - return Task.FromResult((T)Convert.ChangeType(config.StubResponse, typeof(T))); + case "personal_sign" : case "eth_signTypedData": case "eth_sendTransaction": + return (T) Convert.ChangeType(config.StubResponse, typeof(T)); default: - return Request(method, parameters); - } - } - - // Direct RPC request via WalletConnect RPC url. - private async Task Request(string method, params object[] parameters) - { - // Using WalletConnect Blockchain API: https://docs.walletconnect.com/cloud/blockchain-api - var url = $"https://rpc.walletconnect.com/v1?chainId=eip155:{chainConfig.ChainId}&projectId={config.ProjectId}"; + // Direct RPC request via WalletConnect RPC url. + // Using WalletConnect Blockchain API: https://docs.walletconnect.com/cloud/blockchain-api + var url = $"https://rpc.walletconnect.com/v1?chainId=eip155:{chainConfig.ChainId}&projectId={config.ProjectId}"; - string body = JsonConvert.SerializeObject(new RpcRequestMessage(Guid.NewGuid().ToString(), method, parameters)); + string body = JsonConvert.SerializeObject(new RpcRequestMessage(Guid.NewGuid().ToString(), method, parameters)); - var rawResult = await httpClient.PostRaw(url, body, "application/json"); + var rawResult = await httpClient.PostRaw(url, body, "application/json"); - RpcResponseMessage response = JsonConvert.DeserializeObject(rawResult.Response); + RpcResponseMessage response = JsonConvert.DeserializeObject(rawResult.Response); - return response.Result.ToObject(); + return response.Result.ToObject(); + } } } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming.HyperPlay/HyperPlayProvider.cs b/src/ChainSafe.Gaming.HyperPlay/HyperPlayProvider.cs index b2f34687d..350a37738 100644 --- a/src/ChainSafe.Gaming.HyperPlay/HyperPlayProvider.cs +++ b/src/ChainSafe.Gaming.HyperPlay/HyperPlayProvider.cs @@ -24,7 +24,7 @@ public class HyperPlayProvider : WalletProvider private readonly IHyperPlayConfig config; private readonly IHyperPlayData data; private readonly DataStorage dataStorage; - private readonly IHttpClient httpClient; + private readonly Web3Environment environment; private readonly IChainConfig chainConfig; /// @@ -32,17 +32,17 @@ public class HyperPlayProvider : WalletProvider /// /// Injected . /// Injected . - /// Injected . - /// HttpClient to make requests. + /// Injected . + /// Injected . /// ChainConfig to fetch chain data. /// Injected . - public HyperPlayProvider(IHyperPlayConfig config, IHyperPlayData data, DataStorage dataStorage, IHttpClient httpClient, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) - : base(chainRegistryProvider: chainRegistryProvider) + public HyperPlayProvider(IHyperPlayConfig config, IHyperPlayData data, DataStorage dataStorage, Web3Environment environment, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) + : base(environment, chainRegistryProvider, chainConfig) { this.config = config; this.data = data; this.dataStorage = dataStorage; - this.httpClient = httpClient; + this.environment = environment; this.chainConfig = chainConfig; } @@ -97,7 +97,7 @@ public override Task Disconnect() /// RPC request parameters. /// RPC request response type. /// RPC request Response. - public override async Task Perform(string method, params object[] parameters) + public override async Task Request(string method, params object[] parameters) { string body = JsonConvert.SerializeObject(new HyperPlayRequest { @@ -112,7 +112,7 @@ public override async Task Perform(string method, params object[] paramete }, }); - string response = (await httpClient.PostRaw(config.Url, body, "application/json")).Response; + string response = (await environment.HttpClient.PostRaw(config.Url, body, "application/json")).Response; // In case response is just a primitive type like string/number... // Deserializing it directly doesn't work. diff --git a/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs b/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs new file mode 100644 index 000000000..d90988f57 --- /dev/null +++ b/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs @@ -0,0 +1,14 @@ +using Nethereum.Web3.Accounts; + +namespace ChainSafe.Gaming.InProcessSigner +{ + public class AccountProvider + { + public Account Account { get; private set; } = null!; + + public void Initialize(Account account) + { + Account = account; + } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs b/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs index 51d6d045c..e95570357 100644 --- a/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs +++ b/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs @@ -1,12 +1,15 @@ -using System.Threading.Tasks; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; using ChainSafe.Gaming.Evm.Signers; using ChainSafe.Gaming.Web3; -using ChainSafe.Gaming.Web3.Core; using ChainSafe.Gaming.Web3.Core.Evm; using Nethereum.ABI.EIP712; using Nethereum.ABI.FunctionEncoding.Attributes; -using Nethereum.Signer; -using Nethereum.Signer.EIP712; +using Nethereum.Hex.HexConvertors.Extensions; +using Nethereum.Util; +using Nethereum.Web3.Accounts; +using Newtonsoft.Json; namespace ChainSafe.Gaming.InProcessSigner { @@ -15,34 +18,43 @@ namespace ChainSafe.Gaming.InProcessSigner /// public class InProcessSigner : ISigner { - private readonly EthECKey privateKey; - private readonly EthereumMessageSigner messageSigner; + private readonly AccountProvider accountProvider; /// /// Initializes a new instance of the class. /// - /// Injected Config for signer containing a private key. /// Throws Exception if initializing instance fails. - public InProcessSigner(InProcessSignerConfig config) + public InProcessSigner(AccountProvider accountProvider) { - privateKey = config.PrivateKey ?? - throw new Web3Exception($"{nameof(InProcessSignerConfig)}.{nameof(InProcessSignerConfig.PrivateKey)} must be set"); - messageSigner = new(); + this.accountProvider = accountProvider; } + private Account Account => accountProvider.Account; + /// - /// Implementation of using In Process. + /// Public Address. /// /// Public address of signer. - public string PublicAddress => privateKey.GetPublicAddress(); + public string PublicAddress => Account.Address; /// /// Implementation of using In Process. /// /// Message to be signed. /// Hash response of a successfully signed message. - public Task SignMessage(string message) => - Task.FromResult(messageSigner.EncodeUTF8AndSign(message, privateKey)); + public async Task SignMessage(string message) + { + var byteList = new List(); + var bytePrefix = "0x19".HexToByteArray(); + var textBytePrefix = Encoding.UTF8.GetBytes("Ethereum Signed Message:\n" + message.Length); + + byteList.AddRange(bytePrefix); + byteList.AddRange(textBytePrefix); + byteList.AddRange(Encoding.UTF8.GetBytes(message)); + var hash = new Sha3Keccack().CalculateHash(byteList.ToArray()); + + return await Account.AccountSigningService.PersonalSign.SendRequestAsync(hash); + } /// /// Implementation of using In Process. @@ -51,7 +63,7 @@ public Task SignMessage(string message) => /// Message/Data to be signed. /// Type of Data to be signed. /// Hash response of a successfully signed typed data. - public Task SignTypedData(SerializableDomain domain, TStructType message) + public async Task SignTypedData(SerializableDomain domain, TStructType message) { var primaryType = typeof(TStructType).Name; if (StructAttribute.IsStructType(message)) @@ -66,13 +78,8 @@ public Task SignTypedData(SerializableDomain domain, TStruc Types = MemberDescriptionFactory.GetTypesMemberDescription(typeof(SerializableDomain), typeof(TStructType)), Message = MemberValueFactory.CreateFromMessage(message), }; - return Task.FromResult(Eip712TypedDataSigner.Current.SignTypedDataV4(typedData, privateKey)); - } - /// - /// Get private key of . - /// - /// Private key of . - public EthECKey GetKey() => privateKey; + return await Account.AccountSigningService.SignTypedDataV4.SendRequestAsync(JsonConvert.SerializeObject(typedData)); + } } } diff --git a/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs b/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs index b2083d10c..8394431ae 100644 --- a/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs +++ b/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs @@ -3,14 +3,13 @@ using ChainSafe.Gaming.Evm.Providers; using ChainSafe.Gaming.Evm.Signers; using ChainSafe.Gaming.Evm.Transactions; +using ChainSafe.Gaming.InProcessSigner; using ChainSafe.Gaming.Web3; using ChainSafe.Gaming.Web3.Core.Evm; using Nethereum.Hex.HexTypes; using Nethereum.JsonRpc.Client; using Nethereum.RPC.Eth.DTOs; using Nethereum.Web3.Accounts; -using NIpcClient = Nethereum.JsonRpc.IpcClient.IpcClient; -using NWeb3 = Nethereum.Web3.Web3; namespace ChainSafe.Gaming.InProcessTransactionExecutor { @@ -20,45 +19,22 @@ namespace ChainSafe.Gaming.InProcessTransactionExecutor public class InProcessTransactionExecutor : ITransactionExecutor { private readonly IRpcProvider rpcProvider; - private readonly string accountAddress; - - private NWeb3 web3; + private readonly AccountProvider accountProvider; /// /// Initializes a new instance of the class. /// - /// Injected . - /// Injected . + /// Injected . /// Injected . - /// Injected . /// Throws exception if initializing instance fails. - public InProcessTransactionExecutor(ISigner signer, IChainConfig chainConfig, IRpcProvider rpcProvider, IClient rpcClient) + public InProcessTransactionExecutor(AccountProvider accountProvider, IRpcProvider rpcProvider) { - // It should be possible to set up other signers to work with this as well. - // However, does it make sense to let a remote wallet sign a transaction, but - // broadcast it locally? I think not. - var privateKey = (signer as InProcessSigner.InProcessSigner)?.GetKey() ?? - throw new Web3Exception($"{nameof(InProcessTransactionExecutor)} only supports {nameof(InProcessSigner.InProcessSigner)}"); - accountAddress = privateKey.GetPublicAddress(); - var account = new Account(privateKey); - - if (chainConfig.Rpc is not null && !string.Empty.Equals(chainConfig.Rpc)) - { - web3 = new NWeb3(account, rpcClient); - } - else if (chainConfig.Ipc is not null && !string.Empty.Equals(chainConfig.Ipc)) - { - var client = new NIpcClient(chainConfig.Rpc); - web3 = new NWeb3(client); - } - else - { - throw new Web3Exception($"{nameof(IChainConfig)} should have at least one communication method set."); - } - this.rpcProvider = rpcProvider; + this.accountProvider = accountProvider; } + private Account Account => accountProvider.Account; + /// /// Implementation of . /// Send a transaction using Wallet Connect. @@ -67,11 +43,11 @@ public InProcessTransactionExecutor(ISigner signer, IChainConfig chainConfig, IR /// Transaction to send. /// Hash response of a successfully executed transaction. /// Throws Exception if executing transaction fails. - public async Task SendTransaction(TransactionRequest transaction) + public virtual async Task SendTransaction(TransactionRequest transaction) { if (string.IsNullOrEmpty(transaction.From)) { - transaction.From = accountAddress; + transaction.From = Account.Address; } if (transaction.GasPrice == null && transaction.MaxFeePerGas == null) @@ -107,9 +83,9 @@ public async Task SendTransaction(TransactionRequest transa try { - var signedTransaction = await web3.TransactionManager.SignTransactionAsync(txInput); - var txHash = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync(signedTransaction); - return await rpcProvider.GetTransaction(txHash); + var receipt = await Account.TransactionManager.SendTransactionAndWaitForReceiptAsync(txInput); + + return await rpcProvider.GetTransaction(receipt.TransactionHash); } catch (Exception ex) { diff --git a/src/ChainSafe.Gaming.Unity.MetaMask/MetaMaskProvider.cs b/src/ChainSafe.Gaming.Unity.MetaMask/MetaMaskProvider.cs index 6810199f7..cfc9f901c 100644 --- a/src/ChainSafe.Gaming.Unity.MetaMask/MetaMaskProvider.cs +++ b/src/ChainSafe.Gaming.Unity.MetaMask/MetaMaskProvider.cs @@ -24,23 +24,20 @@ public class MetaMaskProvider : WalletProvider /// /// Initializes a new instance of the class. /// - /// Common Logger used for logging messages and errors. + /// Injected . /// Injected . - /// Injected . /// Injected . - /// Injected . - public MetaMaskProvider(ILogWriter logWriter, IAnalyticsClient analyticsClient, IChainConfig chainConfig, IProjectConfig projectConfig, ChainRegistryProvider chainRegistryProvider) - : base( - chainRegistryProvider: chainRegistryProvider) + public MetaMaskProvider(Web3Environment environment, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) + : base(environment, chainRegistryProvider, chainConfig) { - this.logWriter = logWriter; + logWriter = environment.LogWriter; this.chainConfig = chainConfig; - this.analyticsClient = analyticsClient; + analyticsClient = environment.AnalyticsClient; this.chainRegistryProvider = chainRegistryProvider; if (Application.isEditor || Application.platform != RuntimePlatform.WebGLPlayer) { - this.logWriter.LogError("You need to build to WebGL platform to run Nethereum.Metamask.Unity"); + logWriter.LogError("You need to build to WebGL platform to run Nethereum.Metamask.Unity"); return; } @@ -65,7 +62,7 @@ public override Task Disconnect() return Task.CompletedTask; } - public override async Task Perform(string method, params object[] parameters) + public override async Task Request(string method, params object[] parameters) { var response = await metaMaskController.Request(method, parameters); diff --git a/src/ChainSafe.Gaming.WalletConnect/WalletConnectProvider.cs b/src/ChainSafe.Gaming.WalletConnect/WalletConnectProvider.cs index fab8f6531..125eb5ebc 100644 --- a/src/ChainSafe.Gaming.WalletConnect/WalletConnectProvider.cs +++ b/src/ChainSafe.Gaming.WalletConnect/WalletConnectProvider.cs @@ -55,25 +55,22 @@ public class WalletConnectProvider : WalletProvider, ILifecycleParticipant, ICon public WalletConnectProvider( IWalletConnectConfig config, DataStorage storage, - ILogWriter logWriter, IChainConfig chainConfig, - IOperatingSystemMediator osMediator, IWalletRegistry walletRegistry, RedirectionHandler redirection, - IHttpClient httpClient, - IAnalyticsClient analyticsClient, + Web3Environment environment, ChainRegistryProvider chainRegistryProvider) - : base(chainRegistryProvider: chainRegistryProvider) + : base(environment, chainRegistryProvider, chainConfig) { - this.analyticsClient = analyticsClient; + analyticsClient = environment.AnalyticsClient; this.redirection = redirection; this.walletRegistry = walletRegistry; - this.osMediator = osMediator; + osMediator = environment.OperatingSystem; this.chainConfig = chainConfig; this.storage = storage; this.config = config; - this.logWriter = logWriter; - this.httpClient = httpClient; + logWriter = environment.LogWriter; + httpClient = environment.HttpClient; } public bool StoredSessionAvailable => localData.SessionTopic != null; @@ -351,7 +348,7 @@ private async Task RenewSession() WCLogger.Log("Renewed session successfully."); } - public override async Task Perform(string method, params object[] parameters) + public override async Task Request(string method, params object[] parameters) { if (!connected) { @@ -488,7 +485,19 @@ async Task MakeRequest() default: try { - return await Request(method, parameters); + // 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(rawResult.Response); + + return response.Result.ToObject(); } catch (Exception e) { @@ -496,22 +505,5 @@ async Task MakeRequest() } } } - - // Direct RPC request via WalletConnect RPC url. - private async Task Request(string method, params object[] parameters) - { - 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(rawResult.Response); - - return response.Result.ToObject(); - } } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/Web3/Core/Environment/Web3Environment.cs b/src/ChainSafe.Gaming/Web3/Core/Environment/Web3Environment.cs index d938cd672..017e2c744 100644 --- a/src/ChainSafe.Gaming/Web3/Core/Environment/Web3Environment.cs +++ b/src/ChainSafe.Gaming/Web3/Core/Environment/Web3Environment.cs @@ -1,3 +1,4 @@ +using ChainSafe.Gaming.LocalStorage; using ChainSafe.Gaming.Web3.Analytics; namespace ChainSafe.Gaming.Web3.Environment diff --git a/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientConfig.cs b/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientConfig.cs deleted file mode 100644 index ec6d7da60..000000000 --- a/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace ChainSafe.Gaming.Evm.Providers -{ - [Serializable] - public class RpcClientConfig - { - /// - /// (Optional) Url of RPC Node. - /// - public string RpcNodeUrl { get; set; } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientExtensions.cs b/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientExtensions.cs index a9438e58d..339034b6e 100644 --- a/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientExtensions.cs +++ b/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientExtensions.cs @@ -9,29 +9,6 @@ namespace ChainSafe.Gaming.Evm.JsonRpc { public static class RpcClientExtensions { - private static readonly RpcClientConfig DefaultClientConfig = new(); - - /// - /// Binds JSON RPC implementation of EVM Provider to Web3. - /// - /// The same service collection that was passed in. This enables fluent style. - public static IWeb3ServiceCollection UseRpcProvider(this IWeb3ServiceCollection collection, RpcClientConfig config) - { - collection.ConfigureRpcProvider(config); - collection.UseRpcProvider(); - return collection; - } - - /// - /// Configures JSON RPC implementation of EVM Provider. - /// - /// The same service collection that was passed in. This enables fluent style. - public static IWeb3ServiceCollection ConfigureRpcProvider(this IWeb3ServiceCollection collection, RpcClientConfig config) - { - collection.Replace(ServiceDescriptor.Singleton(config)); - return collection; - } - /// /// Binds JSON RPC implementation of EVM Provider to Web3. /// @@ -39,7 +16,6 @@ public static IWeb3ServiceCollection ConfigureRpcProvider(this IWeb3ServiceColle public static IWeb3ServiceCollection UseRpcProvider(this IWeb3ServiceCollection collection) { collection.AssertServiceNotBound(); - collection.TryAddSingleton(DefaultClientConfig); collection.AddSingleton(); collection.AssertServiceNotBound(); diff --git a/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientProvider.cs b/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientProvider.cs index 0c3ea01e7..e2125416e 100644 --- a/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientProvider.cs +++ b/src/ChainSafe.Gaming/Web3/Evm/JsonRpc/RpcClientProvider.cs @@ -14,57 +14,45 @@ namespace ChainSafe.Gaming.Evm.Providers { public class RpcClientProvider : ClientBase, IRpcProvider, ILifecycleParticipant { - private readonly RpcClientConfig config; + private readonly string rpcNodeUrl; private readonly Web3Environment environment; private readonly ChainRegistryProvider chainRegistryProvider; private readonly IChainConfig chainConfig; - private Network.Network network; - public RpcClientProvider( - RpcClientConfig config, Web3Environment environment, ChainRegistryProvider chainRegistryProvider, IChainConfig chainConfig) { this.chainRegistryProvider = chainRegistryProvider; this.environment = environment; - this.config = config; this.chainConfig = chainConfig; - - if (string.IsNullOrEmpty(this.config.RpcNodeUrl)) - { - this.config.RpcNodeUrl = chainConfig.Rpc; - } + rpcNodeUrl = chainConfig.Rpc; } - public Network.Network LastKnownNetwork - { - get => network; - protected set => network = value; - } + public Network.Network LastKnownNetwork { get; private set; } public async ValueTask WillStartAsync() { - if (network is null || network.ChainId == 0) + if (LastKnownNetwork is null || LastKnownNetwork.ChainId == 0) { if (ulong.TryParse(chainConfig.ChainId, out var chainId)) { var chain = await chainRegistryProvider.GetChain(chainId); - network = new Network.Network() + LastKnownNetwork = new Network.Network() { ChainId = chainId, Name = chain?.Name, }; } - network = await RefreshNetwork(); + LastKnownNetwork = await RefreshNetwork(); } } public ValueTask WillStopAsync() => new(Task.CompletedTask); - public async Task DetectNetwork() + public async Task RefreshNetwork() { // TODO: cache var chainIdHexString = await Perform("eth_chainId"); @@ -75,25 +63,17 @@ public async ValueTask WillStartAsync() throw new Web3Exception("Couldn't detect network"); } + if (chainId == LastKnownNetwork.ChainId) + { + return LastKnownNetwork; + } + var chain = await chainRegistryProvider.GetChain(chainId); return chain != null ? new Network.Network { Name = chain.Name, ChainId = chainId } : new Network.Network { Name = "Unknown", ChainId = chainId }; } - public async Task RefreshNetwork() - { - var currentNetwork = await DetectNetwork(); - - if (network != null && network.ChainId == currentNetwork.ChainId) - { - return network; - } - - network = currentNetwork; - return network; - } - public async Task Perform(string method, params object[] parameters) { // parameters should be skipped or be an empty array if there are none @@ -142,7 +122,7 @@ protected override async Task SendAsync(RpcRequestMessage[ private async Task SendAsyncInternally(string body) { - var result = await environment.HttpClient.PostRaw(config.RpcNodeUrl, body, "application/json"); + var result = await environment.HttpClient.PostRaw(rpcNodeUrl, body, "application/json"); return JsonConvert.DeserializeObject(result.Response); } diff --git a/src/ChainSafe.Gaming/Web3/Evm/Wallet/IWalletProvider.cs b/src/ChainSafe.Gaming/Web3/Evm/Wallet/IWalletProvider.cs index 28f97190a..5b30f9bbb 100644 --- a/src/ChainSafe.Gaming/Web3/Evm/Wallet/IWalletProvider.cs +++ b/src/ChainSafe.Gaming/Web3/Evm/Wallet/IWalletProvider.cs @@ -19,5 +19,7 @@ public interface IWalletProvider : IRpcProvider /// /// Awaitable disconnect Task. Task Disconnect(); + + Task Request(string method, params object[] parameters); } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletProvider.cs b/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletProvider.cs index 933db7f74..b3f62237c 100644 --- a/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletProvider.cs +++ b/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletProvider.cs @@ -2,6 +2,7 @@ using ChainSafe.Gaming.Evm; using ChainSafe.Gaming.Evm.Network; using ChainSafe.Gaming.Evm.Providers; +using ChainSafe.Gaming.Web3.Environment; using Nethereum.Hex.HexTypes; namespace ChainSafe.Gaming.Web3.Evm.Wallet @@ -9,43 +10,23 @@ namespace ChainSafe.Gaming.Web3.Evm.Wallet /// /// Concrete implementation of . /// - public abstract class WalletProvider : IWalletProvider + public abstract class WalletProvider : RpcClientProvider, IWalletProvider { - private readonly ChainRegistryProvider chainRegistryProvider; - /// /// Initializes a new instance of the class. /// + /// Injected . /// Injected . - protected WalletProvider(ChainRegistryProvider chainRegistryProvider) - { - this.chainRegistryProvider = chainRegistryProvider; - } - - public Network LastKnownNetwork { get; private set; } - - async Task IRpcProvider.RefreshNetwork() + /// Injected . + protected WalletProvider(Web3Environment environment, ChainRegistryProvider chainRegistryProvider, IChainConfig chainConfig) + : base(environment, chainRegistryProvider, chainConfig) { - string chainIdHex = await Perform("eth_chainId"); - - ulong chainId = new HexBigInteger(chainIdHex).ToUlong(); - - if (chainId <= 0) - { - throw new Web3Exception("Couldn't detect network."); - } - - var chain = await chainRegistryProvider.GetChain(chainId); - - return chain != null - ? new Network { Name = chain.Name, ChainId = chainId } - : new Network { Name = "Unknown", ChainId = chainId }; } public abstract Task Connect(); public abstract Task Disconnect(); - public abstract Task Perform(string method, params object[] parameters); + public abstract Task Request(string method, params object[] parameters); } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletSigner.cs b/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletSigner.cs index f2b6931e9..cd81ed8f9 100644 --- a/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletSigner.cs +++ b/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletSigner.cs @@ -33,7 +33,7 @@ public virtual async ValueTask WillStartAsync() public virtual async Task SignMessage(string message) { - string hash = await walletProvider.Perform(walletConfig.SignMessageRpcMethodName, message, PublicAddress); + string hash = await walletProvider.Request(walletConfig.SignMessageRpcMethodName, message, PublicAddress); return hash.AssertSignatureValid(message, PublicAddress); } @@ -42,7 +42,7 @@ public virtual async Task SignTypedData(SerializableDomain { SerializableTypedData typedData = new SerializableTypedData(domain, message); - string hash = await walletProvider.Perform(walletConfig.SignTypedMessageRpcMethodName, PublicAddress, typedData); + string hash = await walletProvider.Request(walletConfig.SignTypedMessageRpcMethodName, PublicAddress, typedData); return hash.AssertTypedDataSignatureValid(typedData, PublicAddress); } diff --git a/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletTransactionExecutor.cs b/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletTransactionExecutor.cs index 5974a645c..ba651b192 100644 --- a/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletTransactionExecutor.cs +++ b/src/ChainSafe.Gaming/Web3/Evm/Wallet/WalletTransactionExecutor.cs @@ -32,7 +32,7 @@ public async Task SendTransaction(TransactionRequest transa transaction.From ??= signer.PublicAddress; transaction.Data ??= "0x"; - string hash = await walletProvider.Perform("eth_sendTransaction", transaction.ToTransactionInput()); + string hash = await walletProvider.Request("eth_sendTransaction", transaction.ToTransactionInput()); hash = hash.AssertTransactionValid(); From 23a7da27ec451f3e362b3ccc93406e9341f307c6 Mon Sep 17 00:00:00 2001 From: rob1997 Date: Thu, 4 Jul 2024 21:52:57 +0300 Subject: [PATCH 2/9] fixed send transaction --- .../Runtime/Web3AuthProvider.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs index ce8b9fafe..8585b552b 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs @@ -53,6 +53,8 @@ public override async Task Connect() var account = new Account(response.privKey); + account.TransactionManager.Client = this; + _accountProvider.Initialize(account); return account.Address; From f7a4bba262e73c2ffce0191da2e1273ccb8b4ac6 Mon Sep 17 00:00:00 2001 From: rob1997 Date: Thu, 4 Jul 2024 22:50:43 +0300 Subject: [PATCH 3/9] fixed signing --- .../InProcessSigner.cs | 32 ++----------------- 1 file changed, 3 insertions(+), 29 deletions(-) diff --git a/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs b/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs index e95570357..e8032cc15 100644 --- a/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs +++ b/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs @@ -1,13 +1,8 @@ -using System.Collections.Generic; -using System.Text; +using System.Text; using System.Threading.Tasks; using ChainSafe.Gaming.Evm.Signers; using ChainSafe.Gaming.Web3; using ChainSafe.Gaming.Web3.Core.Evm; -using Nethereum.ABI.EIP712; -using Nethereum.ABI.FunctionEncoding.Attributes; -using Nethereum.Hex.HexConvertors.Extensions; -using Nethereum.Util; using Nethereum.Web3.Accounts; using Newtonsoft.Json; @@ -44,16 +39,7 @@ public InProcessSigner(AccountProvider accountProvider) /// Hash response of a successfully signed message. public async Task SignMessage(string message) { - var byteList = new List(); - var bytePrefix = "0x19".HexToByteArray(); - var textBytePrefix = Encoding.UTF8.GetBytes("Ethereum Signed Message:\n" + message.Length); - - byteList.AddRange(bytePrefix); - byteList.AddRange(textBytePrefix); - byteList.AddRange(Encoding.UTF8.GetBytes(message)); - var hash = new Sha3Keccack().CalculateHash(byteList.ToArray()); - - return await Account.AccountSigningService.PersonalSign.SendRequestAsync(hash); + return await Account.AccountSigningService.PersonalSign.SendRequestAsync(Encoding.UTF8.GetBytes(message)); } /// @@ -65,19 +51,7 @@ public async Task SignMessage(string message) /// Hash response of a successfully signed typed data. public async Task SignTypedData(SerializableDomain domain, TStructType message) { - var primaryType = typeof(TStructType).Name; - if (StructAttribute.IsStructType(message)) - { - primaryType = StructAttribute.GetAttribute(message).Name; - } - - var typedData = new TypedData - { - PrimaryType = primaryType, - Domain = domain, - Types = MemberDescriptionFactory.GetTypesMemberDescription(typeof(SerializableDomain), typeof(TStructType)), - Message = MemberValueFactory.CreateFromMessage(message), - }; + SerializableTypedData typedData = new SerializableTypedData(domain, message); return await Account.AccountSigningService.SignTypedDataV4.SendRequestAsync(JsonConvert.SerializeObject(typedData)); } From 9f88fe338dc668d490b657cd333fe170d7c8f154 Mon Sep 17 00:00:00 2001 From: rob1997 Date: Fri, 5 Jul 2024 11:02:54 +0300 Subject: [PATCH 4/9] cleanup and docs --- .../Runtime/IWeb3AuthTransactionHandler.cs | 29 ++++++++---- .../Scripts/Web3AuthWalletGUITxManager.cs | 24 +++++----- .../Runtime/Web3AuthEvents.cs | 47 ------------------- .../Runtime/Web3AuthEvents.cs.meta | 3 -- .../Runtime/Web3AuthProvider.cs | 17 +++++++ .../Runtime/Web3AuthSigner.cs | 4 +- .../Runtime/Web3AuthTransactionExecutor.cs | 45 +++++++----------- .../AccountProvider.cs | 10 ++++ .../InProcessTransactionExecutor.cs | 2 - .../Web3/Core/Environment/Web3Environment.cs | 1 - 10 files changed, 80 insertions(+), 102 deletions(-) delete mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthEvents.cs delete mode 100644 Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthEvents.cs.meta diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs index 1e5cfd705..aa96c4a4f 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs @@ -3,18 +3,31 @@ namespace ChainSafe.GamingSdk.Web3Auth { + /// + /// Handles web3Auth Transaction requests, approvals, declines and confirmations. + /// public interface IWeb3AuthTransactionHandler { - public event Action OnTransactionRequested; + /// + /// Invokes when transaction is requested. + /// + public event Action<(string id, TransactionRequest request)> OnTransactionRequested; - public event Action OnTransactionConfirmed; + /// + /// Invokes when transaction is confirmed on block. + /// + public event Action OnTransactionConfirmed; - public void RequestTransaction(TransactionRequested transactionRequested); + /// + /// Transaction got approved. + /// + /// Transaction pool Id of Transaction that was approved. + public void TransactionApproved(string transactionId); - public void ConfirmTransaction(TransactionConfirmed transactionConfirmed); - - public void ApproveTransaction(TransactionApproved transactionApproved); - - public void DeclineTransaction(TransactionDeclined transactionDeclined); + /// + /// Transaction got declined. + /// + /// Transaction pool Id of Transaction that was declined. + public void TransactionDeclined(string transactionId); } } \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUITxManager.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUITxManager.cs index 2920cdfa0..550f2bd66 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUITxManager.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUITxManager.cs @@ -34,7 +34,7 @@ public class Web3AuthWalletGUITxManager : MonoBehaviour private bool _processingTransaction; private IWeb3AuthTransactionHandler _transactionHandler; - private Queue _transactionQueue = new Queue(); + private readonly Queue<(string id, TransactionRequest request)> _transactionQueue = new(); #endregion @@ -65,9 +65,9 @@ private void Awake() /// /// Populates the incoming transaction display. /// - private void OnTransactionRequested(TransactionRequested transactionRequested) + private void OnTransactionRequested((string id, TransactionRequest request) args) { - _transactionQueue.Enqueue(transactionRequested); + _transactionQueue.Enqueue(args); if (_processingTransaction) { @@ -84,7 +84,7 @@ private void OnTransactionRequested(TransactionRequested transactionRequested) /// private void PromptTransactionRequest() { - TransactionRequested transactionRequested = _transactionQueue.Peek(); + var transactionRequested = _transactionQueue.Peek(); incomingTxNotification.SetActive(true); @@ -102,8 +102,8 @@ private void PromptTransactionRequest() incomingTxPlaceHolder.SetActive(false); incomingTxDisplay.SetActive(true); - incomingTxHashText.text = transactionRequested.Transaction.Data; - incomingTxActionText.text = transactionRequested.Transaction.Value?.ToString() ?? "Sign Request"; + incomingTxHashText.text = transactionRequested.request.Data; + incomingTxActionText.text = transactionRequested.request.Value?.ToString() ?? "Sign Request"; } /// @@ -111,9 +111,9 @@ private void PromptTransactionRequest() /// private void AcceptRequest() { - TransactionRequested transactionRequested = _transactionQueue.Dequeue(); + var transactionRequested = _transactionQueue.Dequeue(); ShowTxLoadingMenu(); - _transactionHandler.ApproveTransaction(new TransactionApproved(transactionRequested.Id)); + _transactionHandler.TransactionApproved(transactionRequested.id); ResetTransactionDisplay(); } @@ -122,18 +122,16 @@ private void AcceptRequest() /// private void RejectRequest() { - TransactionRequested transactionRequested = _transactionQueue.Dequeue(); - _transactionHandler.DeclineTransaction(new TransactionDeclined(transactionRequested.Id)); + var transactionRequested = _transactionQueue.Dequeue(); + _transactionHandler.TransactionDeclined(transactionRequested.id); ResetTransactionDisplay(); } /// /// Gets transaction data. /// - private void OnTransactionConfirmed(TransactionConfirmed transactionConfirmed) + private void OnTransactionConfirmed(TransactionResponse response) { - var response = transactionConfirmed.Transaction; - var txHash = response.Hash; var txTime = DateTime.Now.ToString("hh:mm tt"); var txAmount = response.Value?.ToString() ?? "0"; diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthEvents.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthEvents.cs deleted file mode 100644 index 1bdf7f160..000000000 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthEvents.cs +++ /dev/null @@ -1,47 +0,0 @@ -using ChainSafe.Gaming.Evm.Transactions; - -namespace ChainSafe.GamingSdk.Web3Auth -{ - public struct TransactionRequested - { - public string Id { get; private set; } - - public TransactionRequest Transaction { get; private set; } - - public TransactionRequested(string id, TransactionRequest transaction) - { - Id = id; - Transaction = transaction; - } - } - - public struct TransactionConfirmed - { - public TransactionResponse Transaction { get; private set; } - - public TransactionConfirmed(TransactionResponse transaction) - { - Transaction = transaction; - } - } - - public struct TransactionApproved - { - public string Id { get; private set; } - - public TransactionApproved(string id) - { - Id = id; - } - } - - public struct TransactionDeclined - { - public string Id { get; private set; } - - public TransactionDeclined(string id) - { - Id = id; - } - } -} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthEvents.cs.meta b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthEvents.cs.meta deleted file mode 100644 index 3c732d5c6..000000000 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthEvents.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 96637bb8ac1a4b758de8609db700950f -timeCreated: 1718953740 \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs index 8585b552b..aa11311f5 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs @@ -8,6 +8,9 @@ using Nethereum.Web3.Accounts; using UnityEngine; +/// +/// Web3Auth provider allowing users to connect a Web3Auth wallet. +/// public class Web3AuthProvider : WalletProvider { private readonly Web3AuthWalletConfig _config; @@ -23,6 +26,10 @@ public Web3AuthProvider(Web3AuthWalletConfig config, AccountProvider accountProv _accountProvider = accountProvider; } + /// + /// Connects Web3Auth wallet. + /// + /// Connected Account. public override async Task Connect() { _coreInstance = Object.FindObjectOfType(); @@ -65,6 +72,9 @@ private void OnLogin(Web3AuthResponse response) _connectTcs.SetResult(response); } + /// + /// Disconnect Web3Auth wallet. + /// public override async Task Disconnect() { if (_disconnectTcs != null && !_disconnectTcs.Task.IsCompleted) @@ -88,6 +98,13 @@ void OnLogout() } } + /// + /// Make RPC requests to the Web3Auth wallet. + /// + /// RPC request method. + /// RPC request parameters. + /// Type of response. + /// RPC request response. public override Task Request(string method, params object[] parameters) { return Perform(method, parameters); diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs index dffea3f0e..a49c216b9 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs @@ -3,8 +3,10 @@ using ChainSafe.Gaming.Web3.Core; using ChainSafe.Gaming.Web3.Core.Logout; using ChainSafe.Gaming.Web3.Evm.Wallet; -using UnityEngine; +/// +/// Signs using a Web3Auth wallet. +/// public class Web3AuthSigner : InProcessSigner, ILifecycleParticipant, ILogoutHandler { private readonly IWalletProvider _walletProvider; diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs index 9ab2b83d0..6c35ac006 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs @@ -8,14 +8,16 @@ using ChainSafe.Gaming.InProcessTransactionExecutor; using ChainSafe.GamingSdk.Web3Auth; +/// +/// Send Transaction for Web3Auth wallet. +/// public class Web3AuthTransactionExecutor : InProcessTransactionExecutor, IWeb3AuthTransactionHandler { - public event Action OnTransactionRequested; + public event Action<(string id, TransactionRequest request)> OnTransactionRequested; - public event Action OnTransactionConfirmed; + public event Action OnTransactionConfirmed; - private readonly Dictionary> _transactionPool = - new Dictionary>(); + private readonly Dictionary response)> _transactionPool = new(); public Web3AuthTransactionExecutor(AccountProvider accountProvider, IRpcProvider rpcProvider) : base(accountProvider, rpcProvider) { @@ -25,42 +27,31 @@ public override Task SendTransaction(TransactionRequest tra { string id = Guid.NewGuid().ToString(); - var request = new TransactionRequested(id, transaction); - var tcs = new TaskCompletionSource(); + + // Add transaction to pool. + _transactionPool.Add(id, (transaction, tcs)); - _transactionPool.Add(request, tcs); - - RequestTransaction(request); + OnTransactionRequested?.Invoke((id, transaction)); return tcs.Task; } - public void RequestTransaction(TransactionRequested transactionRequested) - { - OnTransactionRequested?.Invoke(transactionRequested); - } - - public void ConfirmTransaction(TransactionConfirmed transactionConfirmed) - { - OnTransactionConfirmed?.Invoke(transactionConfirmed); - } - - public async void ApproveTransaction(TransactionApproved transactionApproved) + public async void TransactionApproved(string transactionId) { - var pair = _transactionPool.Single(t => t.Key.Id == transactionApproved.Id); + var pair = _transactionPool.Single(t => t.Key == transactionId); - var response = await base.SendTransaction(pair.Key.Transaction); + var response = await base.SendTransaction(pair.Value.request); - pair.Value.SetResult(response); + pair.Value.response.SetResult(response); - ConfirmTransaction(new TransactionConfirmed(response)); + OnTransactionConfirmed?.Invoke(response); } - public void DeclineTransaction(TransactionDeclined transactionDeclined) + public void TransactionDeclined(string transactionId) { - var pair = _transactionPool.Single(t => t.Key.Id == transactionDeclined.Id); + var pair = _transactionPool.Single(t => t.Key == transactionId); - pair.Value.SetCanceled(); + pair.Value.response.SetCanceled(); } } diff --git a/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs b/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs index d90988f57..654e9a0f3 100644 --- a/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs +++ b/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs @@ -2,10 +2,20 @@ namespace ChainSafe.Gaming.InProcessSigner { + /// + /// Provides the current connected account. + /// public class AccountProvider { + /// + /// Current connected account. + /// public Account Account { get; private set; } = null!; + /// + /// Initialized provider with the current connected account. + /// + /// Current connected account. public void Initialize(Account account) { Account = account; diff --git a/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs b/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs index 8394431ae..f2c0e2e63 100644 --- a/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs +++ b/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs @@ -1,13 +1,11 @@ using System; using System.Threading.Tasks; using ChainSafe.Gaming.Evm.Providers; -using ChainSafe.Gaming.Evm.Signers; using ChainSafe.Gaming.Evm.Transactions; using ChainSafe.Gaming.InProcessSigner; using ChainSafe.Gaming.Web3; using ChainSafe.Gaming.Web3.Core.Evm; using Nethereum.Hex.HexTypes; -using Nethereum.JsonRpc.Client; using Nethereum.RPC.Eth.DTOs; using Nethereum.Web3.Accounts; diff --git a/src/ChainSafe.Gaming/Web3/Core/Environment/Web3Environment.cs b/src/ChainSafe.Gaming/Web3/Core/Environment/Web3Environment.cs index 017e2c744..d938cd672 100644 --- a/src/ChainSafe.Gaming/Web3/Core/Environment/Web3Environment.cs +++ b/src/ChainSafe.Gaming/Web3/Core/Environment/Web3Environment.cs @@ -1,4 +1,3 @@ -using ChainSafe.Gaming.LocalStorage; using ChainSafe.Gaming.Web3.Analytics; namespace ChainSafe.Gaming.Web3.Environment From 93fd5b3be96263a40e71b135b1e4e7209fa9dace Mon Sep 17 00:00:00 2001 From: rob1997 Date: Fri, 5 Jul 2024 14:47:30 +0300 Subject: [PATCH 5/9] made requested changes --- .../Runtime/IWeb3AuthTransactionHandler.cs | 2 +- .../Scripts/Web3AuthWalletGUITxManager.cs | 20 +++++------ .../Runtime/Web3AuthTransactionExecutor.cs | 35 ++++++++++++------- .../Runtime/Web3AuthWalletExtensions.cs | 2 +- .../Web3/Core/Evm/Dto/TransactionRequest.cs | 3 ++ 5 files changed, 38 insertions(+), 24 deletions(-) diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs index aa96c4a4f..9a120b03b 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/IWeb3AuthTransactionHandler.cs @@ -11,7 +11,7 @@ public interface IWeb3AuthTransactionHandler /// /// Invokes when transaction is requested. /// - public event Action<(string id, TransactionRequest request)> OnTransactionRequested; + public event Action OnTransactionRequested; /// /// Invokes when transaction is confirmed on block. diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUITxManager.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUITxManager.cs index 550f2bd66..b3c79791b 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUITxManager.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUITxManager.cs @@ -34,7 +34,7 @@ public class Web3AuthWalletGUITxManager : MonoBehaviour private bool _processingTransaction; private IWeb3AuthTransactionHandler _transactionHandler; - private readonly Queue<(string id, TransactionRequest request)> _transactionQueue = new(); + private readonly Queue _transactionQueue = new(); #endregion @@ -65,9 +65,9 @@ private void Awake() /// /// Populates the incoming transaction display. /// - private void OnTransactionRequested((string id, TransactionRequest request) args) + private void OnTransactionRequested(TransactionRequest request) { - _transactionQueue.Enqueue(args); + _transactionQueue.Enqueue(request); if (_processingTransaction) { @@ -84,7 +84,7 @@ private void OnTransactionRequested((string id, TransactionRequest request) args /// private void PromptTransactionRequest() { - var transactionRequested = _transactionQueue.Peek(); + var transaction = _transactionQueue.Peek(); incomingTxNotification.SetActive(true); @@ -102,8 +102,8 @@ private void PromptTransactionRequest() incomingTxPlaceHolder.SetActive(false); incomingTxDisplay.SetActive(true); - incomingTxHashText.text = transactionRequested.request.Data; - incomingTxActionText.text = transactionRequested.request.Value?.ToString() ?? "Sign Request"; + incomingTxHashText.text = transaction.Data; + incomingTxActionText.text = transaction.Value?.ToString() ?? "Sign Request"; } /// @@ -111,9 +111,9 @@ private void PromptTransactionRequest() /// private void AcceptRequest() { - var transactionRequested = _transactionQueue.Dequeue(); + var transaction = _transactionQueue.Dequeue(); ShowTxLoadingMenu(); - _transactionHandler.TransactionApproved(transactionRequested.id); + _transactionHandler.TransactionApproved(transaction.Id); ResetTransactionDisplay(); } @@ -122,8 +122,8 @@ private void AcceptRequest() /// private void RejectRequest() { - var transactionRequested = _transactionQueue.Dequeue(); - _transactionHandler.TransactionDeclined(transactionRequested.id); + var transaction = _transactionQueue.Dequeue(); + _transactionHandler.TransactionDeclined(transaction.Id); ResetTransactionDisplay(); } diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs index 6c35ac006..791af882d 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs @@ -6,6 +6,7 @@ using ChainSafe.Gaming.Evm.Transactions; using ChainSafe.Gaming.InProcessSigner; using ChainSafe.Gaming.InProcessTransactionExecutor; +using ChainSafe.Gaming.Web3; using ChainSafe.GamingSdk.Web3Auth; /// @@ -13,7 +14,7 @@ /// public class Web3AuthTransactionExecutor : InProcessTransactionExecutor, IWeb3AuthTransactionHandler { - public event Action<(string id, TransactionRequest request)> OnTransactionRequested; + public event Action OnTransactionRequested; public event Action OnTransactionConfirmed; @@ -25,33 +26,43 @@ public Web3AuthTransactionExecutor(AccountProvider accountProvider, IRpcProvider public override Task SendTransaction(TransactionRequest transaction) { - string id = Guid.NewGuid().ToString(); - + transaction.Id = Guid.NewGuid().ToString(); + var tcs = new TaskCompletionSource(); // Add transaction to pool. - _transactionPool.Add(id, (transaction, tcs)); + _transactionPool.Add(transaction.Id, (transaction, tcs)); - OnTransactionRequested?.Invoke((id, transaction)); + OnTransactionRequested?.Invoke(transaction); return tcs.Task; } public async void TransactionApproved(string transactionId) { - var pair = _transactionPool.Single(t => t.Key == transactionId); - - var response = await base.SendTransaction(pair.Value.request); + if (!_transactionPool.TryGetValue(transactionId, out var transaction)) + { + throw new Web3Exception("Transaction not found in pool."); + } + + var response = await base.SendTransaction(transaction.request); - pair.Value.response.SetResult(response); + transaction.response.SetResult(response); OnTransactionConfirmed?.Invoke(response); + + _transactionPool.Remove(transactionId); } public void TransactionDeclined(string transactionId) { - var pair = _transactionPool.Single(t => t.Key == transactionId); - - pair.Value.response.SetCanceled(); + if (!_transactionPool.TryGetValue(transactionId, out var transaction)) + { + throw new Web3Exception("Transaction not found in pool."); + } + + transaction.response.SetCanceled(); + + _transactionPool.Remove(transactionId); } } diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs index afd485548..ac81646b6 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs @@ -39,7 +39,7 @@ public static IWeb3ServiceCollection UseWeb3AuthWallet(this IWeb3ServiceCollecti collection.AddSingleton(); - collection.Replace(ServiceDescriptor.Singleton(typeof(AccountProvider), new AccountProvider())); + collection.AddSingleton( new AccountProvider()); collection.AddSingleton(); diff --git a/src/ChainSafe.Gaming/Web3/Core/Evm/Dto/TransactionRequest.cs b/src/ChainSafe.Gaming/Web3/Core/Evm/Dto/TransactionRequest.cs index 82d3f8189..87e9c3dcc 100644 --- a/src/ChainSafe.Gaming/Web3/Core/Evm/Dto/TransactionRequest.cs +++ b/src/ChainSafe.Gaming/Web3/Core/Evm/Dto/TransactionRequest.cs @@ -8,6 +8,9 @@ namespace ChainSafe.Gaming.Evm.Transactions { public class TransactionRequest : ICloneable { + [JsonIgnore] + public string Id { get; set; } + /// /// QUANTITY - The transaction type. /// From ad1437544bd73215bb15268282d3ffe98570bd26 Mon Sep 17 00:00:00 2001 From: rob1997 Date: Sat, 6 Jul 2024 10:44:08 +0300 Subject: [PATCH 6/9] fixed WebGL issue with web3auth --- .../Runtime/Web3AuthProvider.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs index aa11311f5..b8dde1f5f 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs @@ -54,7 +54,10 @@ public override async Task Connect() _coreInstance.onLogin += OnLogin; - _coreInstance.login(_config.LoginParams); + if (_config.LoginParams != null) + { + _coreInstance.login(_config.LoginParams); + } var response = await _connectTcs.Task; From e32912090957bb73a553fe5f660cb80c35da6c85 Mon Sep 17 00:00:00 2001 From: rob1997 Date: Tue, 9 Jul 2024 22:24:34 +0300 Subject: [PATCH 7/9] Web3AuthProvider now Inherits IAccountProvider, which provides account instead of AccountProvider. --- .../Scripts/Web3AuthWalletGUIUIManager.cs | 5 ++-- .../Runtime/Web3AuthProvider.cs | 17 +++++++------ .../Runtime/Web3AuthSigner.cs | 2 +- .../Runtime/Web3AuthTransactionExecutor.cs | 2 +- .../Runtime/Web3AuthWalletExtensions.cs | 4 +--- .../AccountProvider.cs | 24 ------------------- .../IAccountProvider.cs | 15 ++++++++++++ .../InProcessSigner.cs | 8 +++---- .../InProcessTransactionExecutor.cs | 10 ++++---- 9 files changed, 38 insertions(+), 49 deletions(-) delete mode 100644 src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs create mode 100644 src/ChainSafe.Gaming.InProcessSigner/IAccountProvider.cs diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs index 7e00814c2..bbf4664fa 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs @@ -3,6 +3,7 @@ using ChainSafe.Gaming.InProcessSigner; using ChainSafe.Gaming.UnityPackage; using ChainSafe.GamingSdk.Web3Auth; +using Nethereum.Web3.Accounts; using TMPro; using UnityEngine; using UnityEngine.EventSystems; @@ -185,9 +186,9 @@ private IEnumerator CheckHoldPrivateKeyButtonInput() /// private void SetPrivateKey() { - var accountProvider = (AccountProvider)Web3Accessor.Web3.ServiceProvider.GetService(typeof(AccountProvider)); + var accountProvider = (IAccountProvider)Web3Accessor.Web3.ServiceProvider.GetService(typeof(IAccountProvider)); - privateKeyText.text = accountProvider.Account.PrivateKey; + privateKeyText.text = ((Account) accountProvider.Account).PrivateKey; } /// diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs index b8dde1f5f..776477a55 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthProvider.cs @@ -5,27 +5,28 @@ using ChainSafe.Gaming.Web3.Environment; using ChainSafe.Gaming.Web3.Evm.Wallet; using ChainSafe.GamingSdk.Web3Auth; +using Nethereum.RPC.Accounts; using Nethereum.Web3.Accounts; using UnityEngine; /// /// Web3Auth provider allowing users to connect a Web3Auth wallet. /// -public class Web3AuthProvider : WalletProvider +public class Web3AuthProvider : WalletProvider, IAccountProvider { private readonly Web3AuthWalletConfig _config; - private readonly AccountProvider _accountProvider; private Web3Auth _coreInstance; private TaskCompletionSource _connectTcs; private TaskCompletionSource _disconnectTcs; - public Web3AuthProvider(Web3AuthWalletConfig config, AccountProvider accountProvider, Web3Environment environment, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) : base(environment, chainRegistryProvider, chainConfig) + public Web3AuthProvider(Web3AuthWalletConfig config, Web3Environment environment, IChainConfig chainConfig, ChainRegistryProvider chainRegistryProvider) : base(environment, chainRegistryProvider, chainConfig) { _config = config; - _accountProvider = accountProvider; } + public IAccount Account { get; private set; } + /// /// Connects Web3Auth wallet. /// @@ -61,13 +62,11 @@ public override async Task Connect() var response = await _connectTcs.Task; - var account = new Account(response.privKey); + Account = new Account(response.privKey); - account.TransactionManager.Client = this; - - _accountProvider.Initialize(account); + Account.TransactionManager.Client = this; - return account.Address; + return Account.Address; } private void OnLogin(Web3AuthResponse response) diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs index a49c216b9..bd9072388 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthSigner.cs @@ -11,7 +11,7 @@ public class Web3AuthSigner : InProcessSigner, ILifecycleParticipant, ILogoutHan { private readonly IWalletProvider _walletProvider; - public Web3AuthSigner(AccountProvider accountProvider, IWalletProvider walletProvider) : base(accountProvider) + public Web3AuthSigner(IAccountProvider accountProvider, IWalletProvider walletProvider) : base(accountProvider) { _walletProvider = walletProvider; } diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs index 791af882d..bce996bed 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthTransactionExecutor.cs @@ -20,7 +20,7 @@ public class Web3AuthTransactionExecutor : InProcessTransactionExecutor, IWeb3Au private readonly Dictionary response)> _transactionPool = new(); - public Web3AuthTransactionExecutor(AccountProvider accountProvider, IRpcProvider rpcProvider) : base(accountProvider, rpcProvider) + public Web3AuthTransactionExecutor(IAccountProvider accountProvider, IRpcProvider rpcProvider) : base(accountProvider, rpcProvider) { } diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs index ac81646b6..abb119638 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthWalletExtensions.cs @@ -37,9 +37,7 @@ public static IWeb3ServiceCollection UseWeb3AuthWallet(this IWeb3ServiceCollecti collection.AssertServiceNotBound(); collection.AssertServiceNotBound(); - collection.AddSingleton(); - - collection.AddSingleton( new AccountProvider()); + collection.AddSingleton(); collection.AddSingleton(); diff --git a/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs b/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs deleted file mode 100644 index 654e9a0f3..000000000 --- a/src/ChainSafe.Gaming.InProcessSigner/AccountProvider.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Nethereum.Web3.Accounts; - -namespace ChainSafe.Gaming.InProcessSigner -{ - /// - /// Provides the current connected account. - /// - public class AccountProvider - { - /// - /// Current connected account. - /// - public Account Account { get; private set; } = null!; - - /// - /// Initialized provider with the current connected account. - /// - /// Current connected account. - public void Initialize(Account account) - { - Account = account; - } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.InProcessSigner/IAccountProvider.cs b/src/ChainSafe.Gaming.InProcessSigner/IAccountProvider.cs new file mode 100644 index 000000000..dfb91b37e --- /dev/null +++ b/src/ChainSafe.Gaming.InProcessSigner/IAccountProvider.cs @@ -0,0 +1,15 @@ +using Nethereum.RPC.Accounts; + +namespace ChainSafe.Gaming.InProcessSigner +{ + /// + /// Provides the current connected account. + /// + public interface IAccountProvider + { + /// + /// Current connected account. + /// + public IAccount Account { get; } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs b/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs index e8032cc15..9638d890a 100644 --- a/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs +++ b/src/ChainSafe.Gaming.InProcessSigner/InProcessSigner.cs @@ -3,7 +3,7 @@ using ChainSafe.Gaming.Evm.Signers; using ChainSafe.Gaming.Web3; using ChainSafe.Gaming.Web3.Core.Evm; -using Nethereum.Web3.Accounts; +using Nethereum.RPC.Accounts; using Newtonsoft.Json; namespace ChainSafe.Gaming.InProcessSigner @@ -13,18 +13,18 @@ namespace ChainSafe.Gaming.InProcessSigner /// public class InProcessSigner : ISigner { - private readonly AccountProvider accountProvider; + private readonly IAccountProvider accountProvider; /// /// Initializes a new instance of the class. /// /// Throws Exception if initializing instance fails. - public InProcessSigner(AccountProvider accountProvider) + public InProcessSigner(IAccountProvider accountProvider) { this.accountProvider = accountProvider; } - private Account Account => accountProvider.Account; + private IAccount Account => accountProvider.Account; /// /// Public Address. diff --git a/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs b/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs index f2c0e2e63..a00ab3bca 100644 --- a/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs +++ b/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs @@ -6,8 +6,8 @@ using ChainSafe.Gaming.Web3; using ChainSafe.Gaming.Web3.Core.Evm; using Nethereum.Hex.HexTypes; +using Nethereum.RPC.Accounts; using Nethereum.RPC.Eth.DTOs; -using Nethereum.Web3.Accounts; namespace ChainSafe.Gaming.InProcessTransactionExecutor { @@ -17,21 +17,21 @@ namespace ChainSafe.Gaming.InProcessTransactionExecutor public class InProcessTransactionExecutor : ITransactionExecutor { private readonly IRpcProvider rpcProvider; - private readonly AccountProvider accountProvider; + private readonly IAccountProvider accountProvider; /// /// Initializes a new instance of the class. /// - /// Injected . + /// Injected . /// Injected . /// Throws exception if initializing instance fails. - public InProcessTransactionExecutor(AccountProvider accountProvider, IRpcProvider rpcProvider) + public InProcessTransactionExecutor(IAccountProvider accountProvider, IRpcProvider rpcProvider) { this.rpcProvider = rpcProvider; this.accountProvider = accountProvider; } - private Account Account => accountProvider.Account; + private IAccount Account => accountProvider.Account; /// /// Implementation of . From efc82fe3ecee5f78d5632f2cc0fb391d70cde108 Mon Sep 17 00:00:00 2001 From: rob1997 Date: Wed, 10 Jul 2024 17:11:14 +0300 Subject: [PATCH 8/9] HyperPlay fix --- src/ChainSafe.Gaming.HyperPlay/HyperPlayProvider.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ChainSafe.Gaming.HyperPlay/HyperPlayProvider.cs b/src/ChainSafe.Gaming.HyperPlay/HyperPlayProvider.cs index 350a37738..f0c6e72a4 100644 --- a/src/ChainSafe.Gaming.HyperPlay/HyperPlayProvider.cs +++ b/src/ChainSafe.Gaming.HyperPlay/HyperPlayProvider.cs @@ -52,7 +52,7 @@ public HyperPlayProvider(IHyperPlayConfig config, IHyperPlayData data, DataStora /// Signed-in account public address. public override async Task Connect() { - string[] accounts = await Perform("eth_accounts"); + string[] accounts = await Request("eth_accounts"); string account = accounts[0]; @@ -64,7 +64,7 @@ public override async Task Connect() string message = "Sign-in with Ethereum"; - string hash = await Perform("personal_sign", message, account); + string hash = await Request("personal_sign", message, account); hash.AssertSignatureValid(message, account); From 30705810b8a52ba938a28183f19b737f679523d4 Mon Sep 17 00:00:00 2001 From: rob1997 Date: Thu, 11 Jul 2024 09:36:54 +0300 Subject: [PATCH 9/9] requested changes made --- .../WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs index 6e8ee0a06..3b0665492 100644 --- a/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs +++ b/Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUIUIManager.cs @@ -50,6 +50,15 @@ public class Web3AuthWalletGUIUIManager : MonoBehaviour /// private void Start() { + if (Web3Accessor.Web3 == null) + { + Debug.LogError("Web3 instance not set."); + + gameObject.SetActive(false); + + return; + } + InitializeButtons(); originalOrientation = Screen.orientation; walletAddressText.text = Web3Accessor.Web3.Signer.PublicAddress;