Web3GLLight.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Threading.Tasks;
  4. using Newtonsoft.Json;
  5. using UnityEngine;
  6. #if UNITY_WEBGL
  7. public class Web3GLLight
  8. {
  9. [DllImport("__Internal")]
  10. private static extern void ClearResponseJs();
  11. [DllImport("__Internal")]
  12. private static extern string SendAsyncResponse();
  13. [DllImport("__Internal")]
  14. private static extern string SendAsyncError();
  15. [DllImport("__Internal")]
  16. private static extern void SendAsyncJs(string method, string parameters);
  17. public static async Task<string> SendAsync(string method, string parameters)
  18. {
  19. ClearResponseJs();
  20. SendAsyncJs(method, parameters);
  21. var response = "";
  22. var error = "";
  23. while (response == "" && error == "")
  24. {
  25. await new WaitForSeconds(0.1f);
  26. response = SendAsyncResponse();
  27. error = SendAsyncError();
  28. }
  29. if (error != "")
  30. {
  31. var err = JsonConvert.DeserializeObject<WalletError>(error);
  32. throw new WalletException(err!.Code, err.Message);
  33. }
  34. return response;
  35. }
  36. public class WalletError
  37. {
  38. [JsonProperty(PropertyName = "code")] public int Code { get; set; }
  39. [JsonProperty(PropertyName = "message")]
  40. public string Message { get; set; }
  41. }
  42. [Serializable]
  43. public class WalletException : Exception
  44. {
  45. public int code;
  46. public string message;
  47. public WalletException(int code, string message)
  48. {
  49. this.code = code;
  50. this.message = message;
  51. }
  52. }
  53. }
  54. #endif