Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Smart contract call bugfix #115

Merged
merged 6 commits into from
Mar 28, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ private IContract

private Web3 _web3;

private WalletConnectSharp.Unity.WalletConnect WalletConnect =>
ConnectProvider<WalletConnectSharp.Unity.WalletConnect>.GetConnect();

private void Awake()
{
_web3 = new Web3(_providerInfo.HttpProviderURL);
Expand Down Expand Up @@ -131,7 +134,7 @@ public override void SetUseCaseBodyActive(bool isActive)
var sdkInstance = MirageSDKFactory.GetMirageSDKInstance(_providerInfo.HttpProviderURL);

_gameCharacterContract = sdkInstance.GetContract(_gameCharacterContractInfo);

_gameItemContract = sdkInstance.GetContract(_gameItemContractInfo);
_ethHandler = sdkInstance.Eth;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public interface IWalletConnectCommunicator
UniTask<BigInteger> EthChainId();
string GetDefaultAccount(string network);

UniTask<TResponse> Send<TRequest, TResponse>(TRequest data)
UniTask<TResponse> Send<TRequest, TResponse>(TRequest request)
where TRequest : IIdentifiable
where TResponse : IErrorHolder;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,11 @@ public JsonRpcRequest()

[JsonIgnore]
public string Event => Method;

public override string ToString()
{
var jsonStr = JsonConvert.SerializeObject(this);
return jsonStr;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ public class JsonRpcResponse : IEventSource, IErrorHolder
[JsonIgnore]
public string Event => "response:" + ID;

public override string ToString()
{
var jsonStr = JsonConvert.SerializeObject(this);
return jsonStr;
}

public class JsonRpcError
{
[JsonProperty("code")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@ public class EventDelegator : IDisposable
{
private readonly Dictionary<string, List<IEventProvider>> _listeners = new Dictionary<string, List<IEventProvider>>();

public void ListenForGenericResponse<T>(object id, EventHandler<GenericEvent<T>> callback)
{
ListenForGeneric("response:" + id, callback);
}

public void ListenForResponse<T>(object id, EventHandler<JsonRpcResponseEvent<T>> callback)
{
ListenFor("response:" + id, callback);
Expand Down Expand Up @@ -54,11 +49,6 @@ private void SubscribeProvider(string eventId, IEventProvider provider)
listProvider.Add(provider);
}

public bool Trigger<T>(string topic, T obj)
{
return Trigger(topic, JsonConvert.SerializeObject(obj));
}

public bool Trigger(string topic, string json)
{
if (!_listeners.ContainsKey(topic))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,10 @@ public class NetworkMessage

[JsonProperty("silent")]
public bool Silent;

public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ private async void TransportOnMessageReceived(object sender, MessageReceivedEven

var request = JsonConvert.DeserializeObject<JsonRpcRequest>(json);


if (request?.Method != null)
{
EventDelegator.Trigger(request.Method, json);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,12 +339,14 @@ public async UniTask<string> EthSendRawTransaction(string data, Encoding message
return response.Result;
}

public async UniTask<TResponse> Send<TRequest, TResponse>(TRequest data)
public async UniTask<TResponse> Send<TRequest, TResponse>(TRequest request)
where TRequest : IIdentifiable
where TResponse : IErrorHolder
{
var eventCompleted = new UniTaskCompletionSource<TResponse>();

var requestClone = request;

void HandleSendResponse(object sender, JsonRpcResponseEvent<TResponse> @event)
{
var response = @event.Response;
Expand All @@ -358,10 +360,9 @@ void HandleSendResponse(object sender, JsonRpcResponseEvent<TResponse> @event)
}
}

EventDelegator.ListenForResponse<TResponse>(data.ID, HandleSendResponse);

await SendRequest(data);

EventDelegator.ListenForResponse<TResponse>(request.ID, HandleSendResponse);

await SendRequest(request);
OnSend?.Invoke();

return await eventCompleted.Task;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ private async UniTask SendMessage(List<ArraySegment<byte>> queue, WebSocketMessa
// The state of the connection is contained in the context Items dictionary.
bool sending;


lock (_lock)
{
sending = _isSending;
Expand All @@ -192,6 +193,7 @@ private async UniTask SendMessage(List<ArraySegment<byte>> queue, WebSocketMessa
}
}


if (!sending)
{
// Lock with a timeout, just in case.
Expand All @@ -209,18 +211,24 @@ await _socket.CloseAsync(WebSocketCloseStatus.InternalServerError, string.Empty,
var t = _socket.SendAsync(buffer, messageType, true, _cancellationToken);
t.Wait(_cancellationToken);
}
catch (Exception ex)
{
Debug.LogError("Socket SendAsync exception: " + ex.Message + " StackTrace: " + ex.StackTrace);
}
finally
{
Monitor.Exit(_socket);
}

// Note that we've finished sending.

lock (_lock)
{
_isSending = false;
}

// Handle any queued messages.

await HandleQueue(queue, messageType);
}
else
Expand Down Expand Up @@ -258,16 +266,23 @@ private async UniTask HandleQueue(List<ArraySegment<byte>> queue, WebSocketMessa
public void DispatchMessageQueue()
{
// lock mutex, copy queue content and clear the queue.
_messageListMutex.WaitOne();
var messageListCopy = new List<byte[]>();
messageListCopy.AddRange(_messageList);
_messageList.Clear();
// release mutex to allow the websocket to add new messages
_messageListMutex.ReleaseMutex();

foreach (var bytes in messageListCopy)
List<byte[]> messageListCopy = null;
if (_messageList.Count > 0)
{
OnMessage?.Invoke(bytes);
_messageListMutex.WaitOne();
messageListCopy = new List<byte[]>();
messageListCopy.AddRange(_messageList);
_messageList.Clear();
// release mutex to allow the websocket to add new messages
_messageListMutex.ReleaseMutex();
}

if (messageListCopy != null)
{
foreach (var bytes in messageListCopy)
{
OnMessage?.Invoke(bytes);
}
}
}

Expand Down Expand Up @@ -321,7 +336,7 @@ public async UniTask Receive()
}
catch (Exception e)
{
Debug.LogException(e);
Debug.LogError($"WebSocket Receive exception: {e.Message} {e.StackTrace}");
_tokenSource.Cancel();
}
finally
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ public class NativeWebSocketTransport : ITransport

public void Update()
{
#if !UNITY_WEBGL || UNITY_EDITOR
#if !UNITY_WEBGL || UNITY_EDITOR
if (_client?.State == WebSocketState.Open)
{
_client.DispatchMessageQueue();
}
#endif
#endif
}

public async UniTask OnApplicationPause(bool pauseStatus)
Expand Down Expand Up @@ -117,7 +117,6 @@ public async UniTask SendMessage(NetworkMessage message)
else
{
var finalJson = JsonConvert.SerializeObject(message);

await _client.SendText(finalJson);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,6 @@ public async UniTask OnApplicationPause(bool pauseStatus)

public async UniTask Connect()
{
TeardownEvents();
var savedSession = SessionSaveHandler.GetSavedSession();
Logger.AddLog(PackageInfo.Version);

Expand Down Expand Up @@ -291,12 +290,12 @@ public string GetDefaultAccount(string network = null)
return _session.GetDefaultAccount(network);
}

public UniTask<TResponse> Send<TRequest, TResponse>(TRequest data)
public UniTask<TResponse> Send<TRequest, TResponse>(TRequest request)
where TRequest : IIdentifiable
where TResponse : IErrorHolder
{
CheckIfSessionCreated();
return _session.Send<TRequest, TResponse>(data);
return _session.Send<TRequest, TResponse>(request);
}

public UniTask<GenericJsonRpcResponse> GenericRequest(GenericJsonRpcRequest genericRequest)
Expand Down Expand Up @@ -465,6 +464,7 @@ private void HandleSessionCreated()
private async UniTask<WCSessionData> CompleteConnect()
{
SetupDefaultWallet().Forget();
TeardownEvents();
SetupEvents();

var tries = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,14 @@ public async UniTask ListenForEvents()

Update().Forget();


var connectTask = _transport.Connect().AsTask();
await connectTask;


if (connectTask.IsFaulted)
{
Debug.LogError(connectTask.Exception);
Debug.LogError("ContractEventSubscribed " + connectTask.Exception);
}

Debug.Log("Listen for events socket connected");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ namespace MirageSDK.SilentSigning.Implementation
public class SilentSigningProtocol : ISilentSigningHandler
{
public ISilentSigningSessionHandler SessionHandler { get; }
private WalletConnectSharp.Unity.WalletConnect WalletConnect => ConnectProvider<WalletConnectSharp.Unity.WalletConnect>.GetConnect();

private WalletConnectSharp.Unity.WalletConnect WalletConnect =>
ConnectProvider<WalletConnectSharp.Unity.WalletConnect>.GetConnect();

private bool _skipNextDeepLink;

Expand All @@ -28,6 +30,7 @@ public async UniTask<string> RequestSilentSign(long timestamp, long chainId = 1)
var data = new SilentSigningConnectionRequest(timestamp, chainId);
var requestSilentSign =
await WalletConnect.Send<SilentSigningConnectionRequest, SilentSigningResponse>(data);

if (!requestSilentSign.IsError)
{
SessionHandler.SaveSilentSession(requestSilentSign.Result);
Expand All @@ -44,7 +47,8 @@ public UniTask DisconnectSilentSign()
return WalletConnect.Send<SilentSigningDisconnectRequest, SilentSigningResponse>(data);
}

public async UniTask<string> SendSilentTransaction(string from, string to, string data = null, string value = null,
public async UniTask<string> SendSilentTransaction(string from, string to, string data = null,
string value = null,
string gas = null,
string gasPrice = null, string nonce = null)
{
Expand Down
4 changes: 4 additions & 0 deletions Assets/MirageSDK/Runtime/Utils/EventAwaiter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using MirageSDK.Core.Infrastructure;
using MirageSDK.Data;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace MirageSDK.Utils
{
Expand Down Expand Up @@ -44,8 +45,10 @@ public async UniTask StartWaiting(EventFilterRequest<TEventDto> filtersRequest)
{
_receiveEventCompletionSource = new UniTaskCompletionSource<TEventDto>();
_eventSubscriber.ListenForEvents().Forget();

await _eventSubscriber.SocketOpeningTask;


try
{
_subscription = await _eventSubscriber.Subscribe(
Expand All @@ -56,6 +59,7 @@ public async UniTask StartWaiting(EventFilterRequest<TEventDto> filtersRequest)
}
catch (Exception e)
{
Debug.LogError("EventAwaiter exception: " + e.Message);
_receiveEventCompletionSource.TrySetException(e);
}
}
Expand Down