Nethereum / Nethereum.Playground

Compile and run Nethereum snippets on the browser
MIT License
28 stars 17 forks source link

Example: Transactions Contract, generate txn input and sign in other server. #38

Open juanfranblanco opened 3 years ago

juanfranblanco commented 3 years ago
using Nethereum.Web3;
using Nethereum.ABI.FunctionEncoding.Attributes;
using Nethereum.Contracts.CQS;
using Nethereum.Util;
using Nethereum.Web3.Accounts;
using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.Contracts;
using Nethereum.Contracts.Extensions;
using System;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;

public class FunctionMessageSigning
{

    [Function("transfer", "bool")]
    public class TransferFunction : FunctionMessage
    {
        [Parameter("address", "_to", 1)]
        public string To { get; set; }

        [Parameter("uint256", "_value", 2)]
        public BigInteger TokenAmount { get; set; }
    }

    ///*** THE MAIN PROGRAM ***
    public static async Task Main()
    {

                 var url = "http://testchain.nethereum.com:8545";
        var web3 = new Web3(url);

// ### Signing a Function / Deployment message online / offline
        var contractAddress = "0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe";
        var receiverAddress = "0x1245695669a9FD93d5F28D9Ec85E40f4cb697BAe";
        var transferHandler = web3.Eth.GetContractTransactionHandler<TransferFunction>();

        var transfer = new TransferFunction()
        {
            To = receiverAddress,
            TokenAmount = 100
        };

                // all other values
                //transfer.Nonce
                //transfer.GasPrice etc
                //to make it fully offline
                //estimate gas
        var transactionInput = await transferHandler.CreateTransactionInputEstimatingGasAsync(contractAddress, transfer);
                //save to file, whatever.

                // other computer offline / online.
                var privateKey = "0x7580e7fb49df1c861f0050fae31c2224c6aba908e116b8da44ee8cd927b990b0";
        var account = new Account(privateKey);

        var web32 = new Web3(account, url);
                //if nonce is not provided / gas price etc will go to the chain to complete these
                web32.TransactionManager.SendTransactionAsync(transactionInput);

    }
}