diff --git a/src/ChainSafe.Gaming.MetaMask.Unity/MetaMaskController.cs b/src/ChainSafe.Gaming.MetaMask.Unity/MetaMaskController.cs index 57923913c..abcaf92bc 100644 --- a/src/ChainSafe.Gaming.MetaMask.Unity/MetaMaskController.cs +++ b/src/ChainSafe.Gaming.MetaMask.Unity/MetaMaskController.cs @@ -17,6 +17,8 @@ public class MetaMaskController : MonoBehaviour { private bool isInitialized; + private TaskCompletionSource connectionTcs; + /// Use this instead of . private ILogWriter logger; @@ -56,7 +58,14 @@ public void Initialize(ILogWriter logWriter) /// Connected account address. public Task Connect() { - var taskCompletionSource = new TaskCompletionSource(); + if (connectionTcs != null && !connectionTcs.Task.IsCompleted) + { + connectionTcs.SetException(new Web3Exception("Metamask connection not completed.")); + + return connectionTcs.Task; + } + + connectionTcs = new TaskCompletionSource(); // Unsubscribe in case we're already subscribed from a previous login. OnAccountConnected -= Connected; @@ -68,9 +77,9 @@ void Connected(string address) { ConnectedAddress = address; - if (!taskCompletionSource.TrySetResult(ConnectedAddress)) + if (!connectionTcs.TrySetResult(ConnectedAddress)) { - taskCompletionSource.SetException(new Web3Exception("Error setting connected account address.")); + connectionTcs.SetException(new Web3Exception("Error setting connected account address.")); } else { @@ -85,7 +94,7 @@ void Connected(string address) } else { - logger.LogError("Metamask is not available, please install it first."); + connectionTcs.SetException(new Web3Exception("Metamask is not available, please install it first.")); // Unsubscribe to event. OnAccountConnected -= Connected; @@ -93,7 +102,7 @@ void Connected(string address) return null; } - return taskCompletionSource.Task; + return connectionTcs.Task; } /// @@ -194,7 +203,14 @@ public void ChainSelected(string chainId) // Callback for displaying an error if operation fails. private void DisplayError(string message) { - logger.LogError(message); + if (connectionTcs != null && !connectionTcs.Task.IsCompleted) + { + connectionTcs.SetException(new Web3Exception(message)); + } + else + { + logger.LogError(message); + } } } } \ No newline at end of file