Skip to content

Commit

Permalink
Smart contract call bugfix (#115)
Browse files Browse the repository at this point in the history
* smart contract fixing wip

* teardown location bugfix

* additional debug logs

* remove debug lines

* format and compile errors

* post review fixes
  • Loading branch information
Antivortex authored Mar 28, 2023
1 parent 2cd2a7a commit aff8a53
Show file tree
Hide file tree
Showing 13 changed files with 63 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,8 @@ private IContract
private IContract
_gameItemContract; //you can find the source in the mirage-smart-contract-example repo in contracts/GameItem.sol

private Web3 _web3;

private void Awake()
{
_web3 = new Web3(_providerInfo.HttpProviderURL);
SubscribeButtonLinks();
}

Expand Down Expand Up @@ -131,7 +128,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 @@ -339,7 +339,7 @@ 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
{
Expand All @@ -358,10 +358,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 @@ -192,6 +192,7 @@ private async UniTask SendMessage(List<ArraySegment<byte>> queue, WebSocketMessa
}
}


if (!sending)
{
// Lock with a timeout, just in case.
Expand All @@ -209,18 +210,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 +265,22 @@ 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[]>(_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 +334,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
3 changes: 3 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,6 +45,7 @@ public async UniTask StartWaiting(EventFilterRequest<TEventDto> filtersRequest)
{
_receiveEventCompletionSource = new UniTaskCompletionSource<TEventDto>();
_eventSubscriber.ListenForEvents().Forget();

await _eventSubscriber.SocketOpeningTask;

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

0 comments on commit aff8a53

Please sign in to comment.