.NET应用和以太坊智能合约的桥梁

Nethereum基本上是目前唯一可用的.NET平台下的web3.js移植包。在这个教程中,我们将首先编写并部署一个简单的智能合约,然后创建一个简单的.NET应用,并使用Nethereum来访问以太坊上的智能合约。Nethereum是通过以太坊节点旳标准RPC接口访问智能合约,因此使用Nethereum可以对接所有的以太坊节点实现,例如geth或parity。

如果你希望快速掌握Netherem的开发,可以访问汇智网的互动教程C#以太坊开发详解,技术问题可以直接咨询课程助教。

智能合约开发与部署

首先安装开发用以太坊节点软件Ganache:

~$ npm install -g ganache-cli

然后安装以太坊开发框架Truffle:

~$ npm install -g truffle

现在创建一个项目目录,进入该目录,并执行truffle init进行初始化:

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

truffle会创建一些新的文件夹:contract、test、migration等。在contract文件夹中,创建一个新的合约文件Vote.sol:

~/hubwiz/contracts$ touch Vote.sol

按如下内容编辑Vote.sol,这个合约只是简单地跟踪两个候选人的得票数,它使用交易发起账户作为投票人,并且每个账户只能投一票:

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,内容如下:

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

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

然后打开项目文件夹下的truffle.js,用以下内容替换:

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

现在打开一个终端,启动ganache:

~$ 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应用中。

汇智网翻译,转载请标明出处。原文链接:Interfacing .NET and Ethereum Blockchain Smart Contracts with Nethereum

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354

推荐阅读更多精彩内容