Examples of Ethereum real combat based on. NET and C #

Source: Internet
Author: User

This is an early version of an article designed to help developers who have a basic understanding of the Ethereum blockchain platform if they want to learn how to use Nethereum. NET Library to program the Ethereum platform.

I'll add more to this article later, but for now, using it to publish. NET + + 's series of C # examples, describes how to use the Nethereum library to perform the most common tasks for the Ethereum blockchain platform.

The most common Tasks list includes the following:

    • 1. Get the Protocol version
    • 2. Get the maximum number of blocks
    • 3. Get account Balances
    • 4. Send Ethernet
    • 5. Wait for the transaction receipt
    • 6. Scan blocks in the block chain
    • 7. List of individual accounts (and their balances)
    • 8. Scan transactions in the blockchain
    • 9. Interacting with existing (deployed) contracts
    • 10. Interacting with events and existing (deployed) contracts
    • 11. Get all active changes
    • 12. Get the contract amount history

Here is the main file for C #:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;using System.threading.tasks;using nethereum.hex.hextypes;using nethereum.web3;namespace MWH.  mynethereum.quickref{static public class Taskexamples {const int unlock_timeout = 2 *;//2 minutes (arbitrary) const int sleep_time = 5 * 1000; 5 Seconds (arbitrary) const int max_timeout = 2 * 60 * 1000; 2 minutes (Arbirtrary)//These static public variables don't represent a recommended pattern static public string last ProtocolVersion = ""; static public string lasttxhash = ""; static public Nethereum.RPC.Eth.DTOs.TransactionReceipt lasttxreceipt = null; static public Hexbiginteger Lastmaxblocknumber = new Hexbiginteger (0), static public async Task Getprotocolversionexample (Web3 web3) {Console.WriteLine ("Getprotocolversionexample:"); var protocolversion = await web3. Eth.ProtocolVersion.SendRequestAsync (); Console.WriteLine ("Protocolversion:\t" + protocolversion.tostring ()); LasTprotocolversion = ProtocolVersion; }static Public Async Task getmaxblockexample (Web3 web3) {Console.WriteLine ("Getmaxblockexample:"); var maxblocknumber = Await web3. Eth.Blocks.GetBlockNumber.SendRequestAsync (); Console.WriteLine ("Maxblocknumber:\t" + maxBlockNumber.Value.ToString ()); Lastmaxblocknumber = Maxblocknumber; }static Public Async Task scanblocksexample (Web3 web3, ulong Startblocknumber, ulong Endblocknumber) {Console.WriteLine ( "Scanblocksexample:"); long txtotalcount = 0; for (ulong blocknumber = startblocknumber; blocknumber <= endblocknumber; blocknumber++) {var blockparameter = new Net Hereum. Rpc. Eth.DTOs.BlockParameter (Blocknumber); var block = await web3. Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync (Blockparameter); var trans = block. transactions; int txcount = trans. Length; Txtotalcount + = Txcount; if (blocknumber% = = 0) console.write ("."); if (blocknumber% 10000 = = 0) {DateTime blockdatetime = Helpers.unixtimestamptodatetime (double) block. TImestamp. Value); Console.WriteLine (blocknumber.tostring () + "" + txtotalcount.tostring () + "" + blockdatetime.tostring ());}} Console.WriteLine (); }static Public Async Task scantxexample (Web3 web3, ulong Startblocknumber, ulong Endblocknumber) {Console.WriteLine ("Sca Ntxexample: "); long txtotalcount = 0; for (ulong blocknumber = startblocknumber; blocknumber <= endblocknumber; blocknumber++) {var blockparameter = new Net Hereum. Rpc. Eth.DTOs.BlockParameter (Blocknumber); var block = await web3. Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync (Blockparameter); var trans = block. transactions; int txcount = trans. Length; Txtotalcount + = Txcount; foreach (var tx in trans) {try {var bn = Tx. Blocknumber.value; var th = Tx. Transactionhash; var ti = Tx. Transactionindex.value;var rpt = await web3. Eth.Transactions.GetTransactionReceipt.SendRequestAsync (TH); var status = rpt. Status.value;var NC = Tx. Nonce.value; var from = Tx. from; Console.WriteLine (Th. ToString () + "" + ti. TostrinG () + "" + from. ToString () + "" + status. ToString ()); var to = Tx. to; if (to = = null) to = "To:null"; var v = Tx. Value.value; var g = Tx. Gas.value; var gp = Tx. Gasprice.value; Console.WriteLine (Th. ToString () + "" + ti. ToString () + "" + NC. ToString () + "" + from. ToString () + "" + to. ToString () + "+ v.tostring () +" "+ g.tostring () +" "+ GP. ToString ()); } catch (Exception ex) {Console.WriteLine ("scantxexample.tx:\t" + ex). ToString ()); if (ex. InnerException = null) Console.WriteLine ("Scantxexample.tx:\t" + ex. Innerexception.tostring ()); }} Console.WriteLine (); }}static Public Async Task getaccountbalanceexample (Web3 web3, String accountaddress) {Console.WriteLine (" Getaccountbalanceexample: "); var Balancewei = await web3. Eth.GetBalance.SendRequestAsync (accountaddress); var balanceether = Web3.Convert.FromWei (Balancewei.value); Console.WriteLine ("Accountaddress:\t" + accountaddress.tostring ()); Console.WriteLine ("Balanceether:\t" + balanceether.tostring ()); }static Public AsynC Task listpersonalaccountsexample (Web3 web3) {Console.WriteLine ("Listpersonalaccountsexample:"); var accounts = await Web3. Personal.ListAccounts.SendRequestAsync (); foreach (var account in accounts) {var Balancewei = await web3. Eth.GetBalance.SendRequestAsync (account); var balanceether = Web3.Convert.FromWei (Balancewei.value); Console.WriteLine ("Account:\t" + account + "Balanceether:\t" + balanceether.tostring ()); }}static Public Async Task sendetherexample (Web3 web3, String fromaddress, String Frompassword, String toaddress, long Ountwei) {Console.WriteLine ("Sendetherexample:"); var unlockresult = await web3. Personal.UnlockAccount.SendRequestAsync (fromaddress, Frompassword, unlock_timeout); var Sendtxhash = await web3. Eth.TransactionManager.SendTransactionAsync (fromaddress, toaddress, New Hexbiginteger (Amountwei)); Console.WriteLine ("Fromaddress:\t" + fromaddress.tostring ()); Console.WriteLine ("Toaddress:\t" + toaddress.tostring ()); Console.WriteLine ("Amountwei:\t" + amountwei.tOstring ()); Console.WriteLine ("Sendtxhash:\t" + sendtxhash.tostring ()); Lasttxhash = Sendtxhash; }static Public Async Task waitfortxreceiptexample (Web3 web3, String txhash) {Console.WriteLine (" Waitfortxreceiptexample: "); int timeoutcount = 0; var txreceipt = await web3. Eth.Transactions.GetTransactionReceipt.SendRequestAsync (Txhash); while (Txreceipt = = null && timeoutcount < Max_timeout) {Console.WriteLine ("Sleeping ..."); Thread.Sleep (Sleep_time); Txreceipt = await web3. Eth.Transactions.GetTransactionReceipt.SendRequestAsync (Txhash); Timeoutcount + = Sleep_time; } Console.WriteLine ("Timeoutcount" + timeoutcount.tostring ()); Lasttxreceipt = Txreceipt; }static Public Async Task interactwithexistingcontractexample (Web3 web3, String fromaddress, String Frompassword, String Contractaddress, String Contractabi) {Console.WriteLine ("Interactwithexistingcontractexample:"); var contract = Web3. Eth.getcontract (Contractabi, contractaddress); var setmessagefunction = contract. GetFunction("Setmsg"); var getmessagefunction = contract. GetFunction ("getmsg"); string nowtimestamp = DateTime.UtcNow.ToString () + "UTC"; Console.WriteLine ("Now:\t" + nowtimestamp); var unlockresult = await web3. Personal.UnlockAccount.SendRequestAsync (fromaddress, Frompassword, unlock_timeout); var txHash1 = await Setmessagefunction.sendtransactionasync (fromaddress, New Hexbiginteger (900000), NULL, 1, "Hello World "); Console.WriteLine ("Txhash1:\t" + txhash1.tostring ()); var txHash2 = await Setmessagefunction.sendtransactionasync (fromaddress, New Hexbiginteger (900000), NULL, 2, Nowtimestamp); Console.WriteLine ("Txhash2:\t" + txhash2.tostring ()); var txReceipt2 = await web3. Eth.Transactions.GetTransactionReceipt.SendRequestAsync (TXHASH2); int timeoutcount = 0; while (txReceipt2 = = null && timeoutcount < Max_timeout) {Console.WriteLine ("Sleeping ..."); Thread.Sleep (Sleep_time); TxReceipt2 = await web3. Eth.Transactions.GetTransactionReceipt.SendRequestAsync (TXHASH2); Timeoutcount + = Sleep_tiME; } Console.WriteLine ("Timeoutcount:\t" + timeoutcount.tostring ()); var txReceipt3 = await Setmessagefunction.sendtransactionandwaitforreceiptasync (fromaddress, New Hexbiginteger (900000), NULL, NULL, 2, Nowtimestamp + "Wait"); Console.WriteLine ("Txreceipt3:\t" + txReceipt3.TransactionHash.ToString ()); Console.WriteLine ("Txreceipt3:\t" + txReceipt3.CumulativeGasUsed.Value.ToString ()); var getResult1 = await Getmessagefunction.callasync<string> (1); Console.WriteLine ("Getresult1:\t" + getresult1.tostring ()); var getResult2 = await getmessagefunction.callasync<string> (2); Console.WriteLine ("Getresult2:\t" + getresult2.tostring ()); }static Public Async Task interactwithexistingcontractwitheventsexample (Web3 web3, String fromaddress, String Frompassword, String contractaddress, String Contractabi) {Console.WriteLine (" Interactwithexistingcontractwitheventsexample: "); var contract = Web3. Eth.getcontract (Contractabi, contractaddress); var setmessagefunction = contract. GetFunction ("sEtmsg "); var getmessagefunction = contract. GetFunction ("getmsg"); var multipliedevent = contract. GetEvent ("Multipliedevent"); var newmessageevent = contract. GetEvent ("newmessageevent"); var filterallmultipliedevent = await multipliedevent.createfilterasync (); var filterallnewmessageevent = await newmessageevent.createfilterasync (); string nowtimestamp = DateTime.UtcNow.ToString () + "UTC"; Console.WriteLine ("Now:\t" + nowtimestamp); var unlockresult = await web3. Personal.UnlockAccount.SendRequestAsync (fromaddress, Frompassword, unlock_timeout); var txHash1 = await Setmessagefunction.sendtransactionasync (fromaddress, New Hexbiginteger (900000), NULL, 1, "Hello World "); Console.WriteLine ("Txhash1:\t" + txhash1.tostring ()); var txHash2 = await Setmessagefunction.sendtransactionasync (fromaddress, New Hexbiginteger (900000), NULL, 2, Nowtimestamp); Console.WriteLine ("Txhash2:\t" + txhash2.tostring ()); var txReceipt2 = await web3. Eth.Transactions.GetTransactionReceipt.SendRequestAsync (TXHASH2); InchT timeoutcount = 0; while (txReceipt2 = = null && timeoutcount < Max_timeout) {Console.WriteLine ("Sleeping ..."); Thread.Sleep (Sleep_time); TxReceipt2 = await web3. Eth.Transactions.GetTransactionReceipt.SendRequestAsync (TXHASH2); Timeoutcount + = Sleep_time; } Console.WriteLine ("Timeoutcount:\t" + timeoutcount.tostring ()); var txReceipt3 = await Setmessagefunction.sendtransactionandwaitforreceiptasync (fromaddress, New Hexbiginteger (900000), NULL, NULL, 2, Nowtimestamp + "Wait"); Console.WriteLine ("Txreceipt3:\t" + txReceipt3.TransactionHash.ToString ()); Console.WriteLine ("Txreceipt3:\t" + txReceipt3.CumulativeGasUsed.Value.ToString ()); var getResult1 = await Getmessagefunction.callasync<string> (1); Console.WriteLine ("Getresult1:\t" + getresult1.tostring ()); var getResult2 = await getmessagefunction.callasync<string> (2); Console.WriteLine ("Getresult2:\t" + getresult2.tostring ()); var logmultipliedevents = await Multipliedevent.getfilterchanges<functionoutputhelpers. Multipliedeventargs> (filterallmultipliedevent); foreach (var mea in logmultipliedevents) {Console.WriteLine ("multipliedevent:\t" + mea). Event.sender + "+ mea". Event.oldProduct.ToString () + "" + MEA. Event.value.ToString () + "" + MEA. Event.newProduct.ToString ()); }var lognewmessageevents = await newmessageevent.getfilterchanges<functionoutputhelpers.newmessageeventargs> (filterallnewmessageevent); foreach (var mea in lognewmessageevents) {Console.WriteLine ("newmessageevent:\t" + mea). Event.sender + "+ mea". Event.ind.ToString () + "" + MEA. Event.msg.ToString ()); }}static Public Async Task getallchangesexample (Web3 web3, String fromaddress, String Frompassword, String contractaddres S, String Contractabi) {Console.WriteLine ("Getallchangesexample:"); var contract = Web3. Eth.getcontract (Contractabi, contractaddress); var newmessageevent = contract. GetEvent ("Newmessageevent"); var filterallnewmessageevent = await newmessageevent.createfilterasync (fromaddress); var lognewmessageEvents = await newmessageevent.getallchanges<functionoutputhelpers.newmessageeventargs> ( Filterallnewmessageevent); foreach (var mea in lognewmessageevents) {Console.WriteLine ("newmessageevent:\t" + mea). Event.sender + "+ mea". Event.ind.ToString () + "" + MEA. Event.msg.ToString ()); }}static Public Async Task getcontractvalueshistoryuniqueoffsetvalueexample (Web3 web3, String contractaddress, Hexbiginteger Recentblocknumber, ulong numberblocks, int offset) {Console.WriteLine (" Getcontractvalueshistoryuniqueoffsetvalueexample: "); string previousvalue =" "; for (ULONG Blocknumber = (ULONG) Recentblocknumber.value; Blocknumber > (ULONG) recentblocknumber.value-numberblocks ; blocknumber--) {var blocknumberparameter = new Nethereum.RPC.Eth.DTOs.BlockParameter (blocknumber); var valueatoffset = Await web3. Eth.GetStorageAt.SendRequestAsync (contractaddress, New Hexbiginteger (offset), blocknumberparameter); if (valueatoffset! = Previousvalue) {var block = await web3. Eth.Blocks.GetBlockWithtransactionsbynumber.sendrequestasync (Blocknumberparameter); DateTime blockdatetime = Helpers.unixtimestamptodatetime ((double) block. Timestamp.value); Console.WriteLine ("Blockdatetime:\t" + blockdatetime.tostring ()); for (int storageoffset = 0; Storageoffset < offset+ 2; storageoffset++) {var valueat = await web3. Eth.GetStorageAt.SendRequestAsync (contractaddress, New Hexbiginteger (Storageoffset), blocknumberparameter); Console.WriteLine ("Value:\t" + blocknumber.tostring () + "" + storageoffset.tostring () + "+ valueat +" "+ Helpers.con Verthex (valueat.substring (2))); } previousvalue = Valueatoffset; } } } }}

Here are some supporting files:

FunctionOutputHelpers.cs

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using Nethereum.web3;using nethereum.abi.functionencoding.attributes;namespace MWH. mynethereum.quickref{static public class Functionoutputhelpers {//Event multipliedevent (//address indexed sender,// int oldproduct,//INT value,//int newproduct//); [Functionoutput] public class Multipliedeventargs {[Parameter ("Address", "sender", 1, true)] the public string sender {get; Set }[parameter ("int", "oldproduct", 2, false)] public int oldproduct {get; set;} [Parameter ("int", "value", 3, false)] public int value {get; set;} [Parameter ("int", "Newproduct", 4, false)] public int newproduct {get; set;}} Event Newmessageevent (//address indexed sender,//uint256 indexed IND,//String msg//); [Functionoutput] public class Newmessageeventargs {[Parameter ("Address", "sender", 1, true)] the public string sender {get; Set }[parameter ("uint256", "IND", 2, true)] public int IND {Get Set }[parameter ("string", "MSG", 3, false)] public string msg {get; set;}} }}

Helpers.cs

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace MWH.  mynethereum.quickref{static public class Helpers {public static string Converthex (String hexstring) {try {string ASCII = String. empty;for (int i = 0; i < hexstring.length; i + = 2) {string hs = string. EMPTY;HS = Hexstring.substring (i, 2); UINT Decval = System.Convert.ToUInt32 (HS, 16); char character = System.Convert.ToChar (Decval); ASCII + = character;} return ASCII; } catch (Exception ex) {Console.WriteLine (ex. Message); }return string. Empty; }public static DateTime Unixtimestamptodatetime (double unixtimestamp) {//Unix timestamp is seconds past epoch System.Dat ETime dtdatetime = new DateTime (1970, 1, 1, 0, 0, 0, 0, SYSTEM.DATETIMEKIND.UTC); Dtdatetime = Dtdatetime.addseconds (Unixtimestamp); // . ToLocalTime (); return dtdatetime; }public static DateTime Javatimestamptodatetime (double javatimestamp) {//Java timestamp is milliseconds past epoch Syste M.datetIME dtdatetime = new DateTime (1970, 1, 1, 0, 0, 0, 0, SYSTEM.DATETIMEKIND.UTC); Dtdatetime = Dtdatetime.addmilliseconds (Javatimestamp); // . ToLocalTime (); return dtdatetime; } }}

The following is the solidity code for the Ethereum contract used to implement these examples:

Test3.sol

pragma solidity 0.4.19;contract Test3 {int public _product;string[5] _msgs;event MultipliedEvent(address indexed sender,int oldProduct,int value,int newProduct);event NewMessageEvent(address indexed sender,uint256 indexed ind,string msg);function Test3() public {_product = 1;}function multiply(int value) public returns(int product) {int old = _product;_product = value * _product;MultipliedEvent( msg.sender, old, value, _product );return _product;}function getProduct() public constant returns(int product) {return _product;}function setMsg(uint256 i, string m) public returns(uint256 mi) {_msgs[i] = m;NewMessageEvent( msg.sender, i, m);return -i;}function getMsg(uint256 index) public constant returns(string m) {return _msgs[index];}}

I think this is a fairly simple and rude way to publish code examples. Have any better suggestions welcome message.

If you want to use C # to develop Ethereum Dapp right away, you can learn the following tutorials:

C # Ethereum, which mainly explains how to use C # development based on. NET Ethereum applications, including account management, status and transaction, intelligent contract development and interaction, filters and events.

Examples of Ethereum real combat based on. NET and C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.