主页 > 官网imtoken安卓版 > .Net 应用程序开发和智能合约访问

.Net 应用程序开发和智能合约访问

官网imtoken安卓版 2023-09-01 05:13:23

本文主要介绍C#编程的.NET应用与以太坊智能合约之间的桥梁,并为大家展示具体内容,希望对大家学习C#编程有所帮助。

C#编程之.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;
     }
 }

接下来在迁移文件夹中新建一个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:

然后打开另一个终端,用 truffle 部署合约:

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

你会在终端输出中看到一个类似如下的合约地址,复制下来以后使用:

Vote: 0xe4e47451aad6c89a6d9e4ad104a7b77ffe1d3b36

.Net 应用程序开发和智能合约访问

新建一个控制台项目并添加对以下开发包的依赖:

然后修改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 candidate1Function = voteContract.GetFunction("candidate1").CallAsync();
             candidate1Function.Wait();             int candidate1 = (int)candidate1Function.Result;
             Task candidate2Function = voteContract.GetFunction("candidate2").CallAsync();
             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 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 应用程序。

本文由Job Coordinate整理发布以太坊智能合约的编程语言,希望对同学们有所帮助。更多详情请关注作业坐标编程语言C#.NET频道!