From 3ac1d71359c958738c97cdf6be6f4ab10125224a Mon Sep 17 00:00:00 2001 From: Brian Levinstein Date: Sat, 15 Jan 2022 02:12:06 -0700 Subject: [PATCH] Add CallContract (and helper methods) for calling contracts via Metamask (alternative to EVM.Call) --- Web3Unity/Scripts/Library/WebGL/Web3GL.cs | 36 ++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/Web3Unity/Scripts/Library/WebGL/Web3GL.cs b/Web3Unity/Scripts/Library/WebGL/Web3GL.cs index 0cffcc56e..2e40944e4 100644 --- a/Web3Unity/Scripts/Library/WebGL/Web3GL.cs +++ b/Web3Unity/Scripts/Library/WebGL/Web3GL.cs @@ -17,6 +17,18 @@ public class Web3GL [DllImport("__Internal")] private static extern void SetContractResponse(string value); + [DllImport("__Internal")] + private static extern void CallContractJs(string method, string abi, string contract, string args); + + [DllImport("__Internal")] + private static extern void ResetCallContractResponse(); + + [DllImport("__Internal")] + private static extern string CallContractResponse(); + + [DllImport("__Internal")] + private static extern string CallContractError(); + [DllImport("__Internal")] private static extern void SendTransactionJs(string to, string value, string gasLimit, string gasPrice); @@ -38,6 +50,28 @@ public class Web3GL [DllImport("__Internal")] private static extern int GetNetwork(); + async public static Task CallContract(string _method, string _abi, string _contract, string _args, float _waitSeconds = 0.1f) + { + ResetCallContractResponse(); + CallContractJs(_method, _abi, _contract, _args); + string response = CallContractResponse(); + string error = CallContractError(); + while (response == "" && error == "") + { + await new WaitForSeconds(_waitSeconds); + response = CallContractResponse(); + error = CallContractError(); + } + ResetCallContractResponse(); + if (error.Length > 0) + { + throw new Exception(error); + } else + { + return response; + } + } + // this function will create a metamask tx for user to confirm. async public static Task SendContract(string _method, string _abi, string _contract, string _args, string _value, string _gasLimit = "", string _gasPrice = "") { @@ -113,4 +147,4 @@ public static int Network() } } -#endif \ No newline at end of file +#endif