如何在.NET應用中訪問以太坊智能合約【Nethereum】

Nethereum基本上是目前惟一可用的.NET平臺下的web3.js移植包。在這個教程中,咱們將首先編寫並部署一個簡單的智能合約,而後建立一個簡單的.NET應用,並使用Nethereum來訪問以太坊上的智能合約。Nethereum是經過以太坊節點旳標準RPC接口訪問智能合約,所以使用Nethereum能夠對接全部的以太坊節點實現,例如geth或parity。web

若是你但願快速掌握Netherem的開發,能夠訪問匯智網的互動教程C#以太坊開發詳解,技術問題能夠直接諮詢課程助教。npm

智能合約開發與部署

首先安裝開發用以太坊節點軟件Ganache:windows

~$ npm install -g ganache-cli

而後安裝以太坊開發框架Truffle:app

~$ npm install -g truffle

如今建立一個項目目錄,進入該目錄,並執行truffle init進行初始化:框架

~$ mkdir demo && cd hubwiz
~/hubwiz$ truffle init

truffle會建立一些新的文件夾:contract、test、migration等。在contract文件夾中,建立一個新的合約文件Vote.sol:ui

~/hubwiz/contracts$ touch Vote.sol

按以下內容編輯Vote.sol,這個合約只是簡單地跟蹤兩個候選人的得票數,它使用交易發起帳戶做爲投票人,而且每一個帳戶只能投一票:url

pragma solidity ^0.4.16;

 contract Vote {

     uint public candidate1;
     uint public candidate2;
     mapping (address => bool) public voted;

     function castVote(uint candidate) public  {
         require(!voted[msg.sender] && (candidate == 1 || candidate == 2));
         if(candidate == 1){
             candidate1++;
         }else{
             candidate2++;            
         }
         voted[msg.sender] = true;
     }
 }

接下來在migration文件夾建立一個新的js文件2_vote.js,內容以下:spa

var vote = artifacts.require("Vote");

 module.exports = function(deployer) {
   // deployment steps
   deployer.deploy(vote);
 };

而後打開項目文件夾下的truffle.js,用如下內容替換:code

module.exports = {
   networks: {
     ganache: {
       host: "127.0.0.1",
       port: 7545,
       network_id: "*" // Match any network id
     }
   }
 };

如今打開一個終端,啓動ganache:blog

~$ ganache-cli

而後打開另外一個終端,用truffle部署合約:

~/hubwiz$ truffle deploy --reset --network ganache

你會看到終端輸出相似下面的合約地址,拷貝下來,後面還要用到:

Vote: 0xe4e47451aad6c89a6d9e4ad104a7b77ffe1d3b36

.Net應用開發與智能合約訪問

建立一個新的控制檯項目,添加對以下開發包的依賴:

  • Nethereum.Web3
  • Nethereum.Contracts

而後按以下內容修改program.cs:

using System;
 using System.Numerics;
 using System.Threading.Tasks;
 using Nethereum.Contracts;
 using Nethereum.Hex.HexTypes;
 using Nethereum.Web3;

 namespace console
 {
     class Program
     {
         static void Main(string[] args)
         {
             //The URL endpoint for the blockchain network.
             string url = "HTTP://localhost:7545";

             //The contract address:合約部署的地址
             string address = "0x345cA3e014Aaf5dcA488057592ee47305D9B3e10";

             //The ABI for the contract.
             string ABI = @"[{'constant':true,'inputs':[],'name':'candidate1','outputs':[{'name':'','type':'uint256'}],'payable':false,'stateMutability':'view','type':'function'},{'constant':false,'inputs':[{'name':'candidate','type':'uint256'}],'name':'castVote','outputs':[],'payable':false,'stateMutability':'nonpayable','type':'function'},{'constant':true,'inputs':[],'name':'candidate2','outputs':[{'name':'','type':'uint256'}],'payable':false,'stateMutability':'view','type':'function'},{'constant':true,'inputs':[{'name':'','type':'address'}],'name':'voted','outputs':[{'name':'','type':'bool'}],'payable':false,'stateMutability':'view','type':'function'}]";

             //Creates the connecto to the network and gets an instance of the contract.
             Web3 web3 = new Web3(url);
             Contract voteContract = web3.Eth.GetContract(ABI, address);

             //Reads the vote count for Candidate 1 and Candidate 2
             Task<BigInteger> candidate1Function = voteContract.GetFunction("candidate1").CallAsync<BigInteger>();
             candidate1Function.Wait();
             int candidate1 = (int)candidate1Function.Result;
             Task<BigInteger> candidate2Function = voteContract.GetFunction("candidate2").CallAsync<BigInteger>();
             candidate2Function.Wait();
             int candidate2 = (int)candidate2Function.Result;            
             Console.WriteLine("Candidate 1 votes: {0}", candidate1);
             Console.WriteLine("Candidate 2 votes: {0}", candidate2);

             //Prompts for the account address.
             Console.Write("Enter the address of your account: ");
             string accountAddress = Console.ReadLine();

             //Prompts for the users vote.
             int vote = 0;
             Console.Write("Press 1 to vote for candidate 1, Press 2 to vote for candidate 2: ");
             Int32.TryParse(Convert.ToChar(Console.Read()).ToString(), out vote);
             Console.WriteLine("You pressed {0}", vote);

             //Executes the vote on the contract.
             try{
                 HexBigInteger gas = new HexBigInteger(new BigInteger(400000));
                 HexBigInteger value = new HexBigInteger(new BigInteger(0));                 
                 Task<string> castVoteFunction = voteContract.GetFunction("castVote").SendTransactionAsync(accountAddress, gas, value, vote);
                 castVoteFunction.Wait();
                 Console.WriteLine("Vote Cast!");
             }catch(Exception e){
                 Console.WriteLine("Error: {0}", e.Message);
             }               
         }
     }
 }

別忘了用你本身部署的合約地址修改上面代碼中的合約地址。如今運行應用,就能夠投票了!

用Nethereum很容易就能夠爲.Net應用添加訪問以太坊智能合約的能力,因爲Nethereum基於.NET平臺,所以它能夠用於.NET Core應用、.NET Standard應用、Xamarin以及各類windows應用中。

原文連接:Nethereum:.NET應用和以太坊智能合約的橋樑 - 匯智網

相關文章
相關標籤/搜索