Guest User

Untitled

a guest
Jun 21st, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. using System;
  2. using System.Threading.Tasks;
  3. using UnityEngine;
  4. using Loom.Unity3d;
  5. using Loom.Nethereum.ABI.FunctionEncoding.Attributes;
  6.  
  7. public class SimpleStoreHandler : MonoBehaviour {
  8.  
  9. // Select an ABI from our project resources
  10. // We got these from the migration script in Truffle
  11. public TextAsset simpleStoreABI;
  12. public TextAsset simpleStoreAddress;
  13.  
  14. // Use this for initialization
  15. public async void Start () {
  16. // Generate new keys for this user
  17. // TODO - Either store these or let the user enter a private key
  18. var privateKey = CryptoUtils.GeneratePrivateKey();
  19. var publicKey = CryptoUtils.PublicKeyFromPrivateKey(privateKey);
  20.  
  21. // Get the contract
  22. var contract = await GetContract(privateKey, publicKey);
  23. // Make a call
  24. await StaticCallContract(contract);
  25. }
  26.  
  27. // Get's the contract as an object
  28. async Task<EvmContract> GetContract(byte[] privateKey, byte[] publicKey)
  29. {
  30. // Get the writer and reader for the Loom node
  31. var writer = RPCClientFactory.Configure()
  32. .WithLogger(Debug.unityLogger)
  33. .WithWebSocket("ws://127.0.0.1:46657/websocket")
  34. .Create();
  35. var reader = RPCClientFactory.Configure()
  36. .WithLogger(Debug.unityLogger)
  37. .WithWebSocket("ws://127.0.0.1:9999/queryws")
  38. .Create();
  39.  
  40. // Create a client object from them
  41. var client = new DAppChainClient(writer, reader)
  42. { Logger = Debug.unityLogger };
  43.  
  44. // required middleware
  45. client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[]
  46. {
  47. new NonceTxMiddleware
  48. {
  49. PublicKey = publicKey,
  50. Client = client
  51. },
  52. new SignedTxMiddleware(privateKey)
  53. });
  54.  
  55. // ABI of the Solidity contract
  56. string abi = simpleStoreABI.ToString();
  57. // Address of the Solidity contract
  58. var contractAddr = Address.FromHexString(simpleStoreAddress.ToString());
  59. // Address of the user
  60. var callerAddr = Address.FromPublicKey(publicKey);
  61. // Return the Contract object
  62. return new EvmContract(client, contractAddr, callerAddr, abi);
  63. }
  64.  
  65. public async Task StaticCallContract(EvmContract contract)
  66. {
  67. if (contract == null)
  68. {
  69. throw new Exception("Not signed in!");
  70. }
  71.  
  72. Debug.Log("Calling smart contract...");
  73.  
  74. int result = await contract.StaticCallSimpleTypeOutputAsync<int>("get");
  75. if (result != null)
  76. {
  77. Debug.Log("Smart contract returned: " + result);
  78. } else
  79. {
  80. Debug.LogError("Smart contract didn't return anything!");
  81. }
  82. }
  83. }
Add Comment
Please, Sign In to add comment