예제 #1
0
 protected QueryHandlerBase(EthCall ethCall, string defaultAddressFrom = null, BlockParameter defaultBlockParameter = null)
 {
     EthCall               = ethCall;
     DefaultAddressFrom    = defaultAddressFrom;
     DefaultBlockParameter = defaultBlockParameter ?? BlockParameter.CreateLatest();
 }
예제 #2
0
 public async Task <HexBigInteger> SendRequestAsync(string id = Constants.DEFAULT_REQUEST_ID)
 {
     return(await SendRequestAsync(BlockParameter.CreateLatest(), id));
 }
 public Task <HexBigInteger> SendRequestAsync(object id = null)
 {
     return(SendRequestAsync(BlockParameter.CreateLatest(), id));
 }
예제 #4
0
        public async Task <object> ExecuteTestAsync(IClient client)
        {
            var ethGetBlockTransactionCountByNumber = new EthGetBlockTransactionCountByNumber(client);

            return(await ethGetBlockTransactionCountByNumber.SendRequestAsync(BlockParameter.CreateLatest()));
        }
        public async Task <object> ExecuteTestAsync(IClient client)
        {
            /* This is the example contract containing an event raised every time we call multiply
             * contract test {
             *
             *  event Multiplied(uint indexed a, address sender);
             *
             *  function multiply(uint a) returns(uint d)
             *  {
             *      Multiplied(a, msg.sender);
             *      return a * 7;
             *
             *  }
             *
             * }*/

            //The contract byte code already compiled
            var contractByteCode =
                "606060405260c08060106000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa1146037576035565b005b604b60048080359060200190919050506061565b6040518082815260200191505060405180910390f35b6000817f10f82b5dc139f3677a16d7bfb70c65252e78143313768d2c52e07db775e1c7ab33604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a260078202905060bb565b91905056";

            //Create a new Eth Send Transanction RPC Handler
            var ethSendTransation = new EthSendTransaction(client);

            //Create the transaction input for the new contract

            //On transaction input the compiled contract is the Data, together with our sender address
            var transactionInput = new TransactionInput();

            transactionInput.Data = contractByteCode;
            transactionInput.From = "0x12890d2cce102216644c59dae5baed380d84830c";
            // retrieve the transaction hash, as we need to get a transaction receipt with the contract address
            var transactionHash = await ethSendTransation.SendRequestAsync(transactionInput);

            //the contract should be mining now

            //Get the transaction receipt using the transactionHash
            var ethGetTransactionReceipt = new EthGetTransactionReceipt(client);
            TransactionReceipt receipt   = null;

            //wait for the contract to be mined to the address
            while (receipt == null)
            {
                receipt = await ethGetTransactionReceipt.SendRequestAsync(transactionHash);
            }

            //sha3 the event call, we can use this to validate our topics

            var eventCallSh3 = await new Web3Sha3(client).SendRequestAsync(new HexString("Multiplied(uint256,address)"));
            //create a filter
            //just listen to anything no more filter topics (ie int indexed number)
            var ethFilterInput = new NewFilterInput();

            ethFilterInput.FromBlock.SetValue(receipt.BlockNumber);
            ethFilterInput.ToBlock = BlockParameter.CreateLatest();
            ethFilterInput.Address = new[] { receipt.ContractAddress };
            //no topics
            //ethFilterInput.Topics = new object[]{};

            var newEthFilter = new EthNewFilter(client);
            var filterId     = await newEthFilter.SendRequestAsync(ethFilterInput);


            //create a transaction which will raise the event
            await SendTransaction(client, transactionInput.From, receipt.ContractAddress);

            //get filter changes
            var ethGetFilterChangesForEthNewFilter = new EthGetFilterChangesForEthNewFilter(client);

            FilterLog[] logs = null;

            while (logs == null || logs.Length < 1)
            {
                //Get the filter changes logs
                logs = await ethGetFilterChangesForEthNewFilter.SendRequestAsync(filterId);

                if (logs.Length > 0)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine("Topic 0: " + logs[0].Topics[0] +
                                  " should be the same as the SH3 encoded event signature " + eventCallSh3);
                    Assert.Equal(logs[0].Topics[0], eventCallSh3);
                    sb.AppendLine("Topic 1: " + logs[0].Topics[1] + " should be 69 hex  0x45, padded");

                    sb.AppendLine("Data " + logs[0].Data + " should be the same as the address padded 32 bytes " +
                                  transactionInput.From);

                    return(sb.ToString());
                }
            }
            throw new Exception("Execution failed");
        }
예제 #6
0
 public EthGetCode(IClient client) : base(client, ApiMethods.eth_getCode.ToString())
 {
     DefaultBlock = BlockParameter.CreateLatest();
 }
예제 #7
0
 public EthCall(IClient client) : base(client, ApiMethods.eth_call.ToString())
 {
     DefaultBlock = BlockParameter.CreateLatest();
 }
예제 #8
0
        static void Main(string[] args)
        {
            var client = new StreamingWebSocketClient("wss://mainnet.infura.io/ws");

            // var client = new StreamingWebSocketClient("ws://127.0.0.1:8546");
            var blockHeaderSubscription = new EthNewBlockHeadersObservableSubscription(client);

            blockHeaderSubscription.GetSubscribeResponseAsObservable().Subscribe(subscriptionId =>
                                                                                 Console.WriteLine("Block Header subscription Id: " + subscriptionId));

            blockHeaderSubscription.GetSubscriptionDataResponsesAsObservable().Subscribe(block =>
                                                                                         Console.WriteLine("New Block: " + block.BlockHash));

            blockHeaderSubscription.GetUnsubscribeResponseAsObservable().Subscribe(response =>
                                                                                   Console.WriteLine("Block Header unsubscribe result: " + response));


            var blockHeaderSubscription2 = new EthNewBlockHeadersSubscription(client);

            blockHeaderSubscription2.SubscriptionDataResponse += (object sender, StreamingEventArgs <Block> e) =>
            {
                Console.WriteLine("New Block from event: " + e.Response.BlockHash);
            };

            blockHeaderSubscription2.GetDataObservable().Subscribe(x =>
                                                                   Console.WriteLine("New Block from observable from event : " + x.BlockHash)
                                                                   );

            var pendingTransactionsSubscription = new EthNewPendingTransactionObservableSubscription(client);

            pendingTransactionsSubscription.GetSubscribeResponseAsObservable().Subscribe(subscriptionId =>
                                                                                         Console.WriteLine("Pending transactions subscription Id: " + subscriptionId));

            pendingTransactionsSubscription.GetSubscriptionDataResponsesAsObservable().Subscribe(transactionHash =>
                                                                                                 Console.WriteLine("New Pending TransactionHash: " + transactionHash));

            pendingTransactionsSubscription.GetUnsubscribeResponseAsObservable().Subscribe(response =>
                                                                                           Console.WriteLine("Pending transactions unsubscribe result: " + response));


            var ethGetBalance = new EthGetBalanceObservableHandler(client);
            var subs          = ethGetBalance.GetResponseAsObservable().Subscribe(balance =>
                                                                                  Console.WriteLine("Balance xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: " + balance.Value.ToString()));

            var ethBlockNumber = new EthBlockNumberObservableHandler(client);

            ethBlockNumber.GetResponseAsObservable().Subscribe(blockNumber =>
                                                               Console.WriteLine("Block number: bbbbbbbbbbbbbb" + blockNumber.Value.ToString()));


            var ethLogs = new EthLogsObservableSubscription(client);

            ethLogs.GetSubscriptionDataResponsesAsObservable().Subscribe(log =>
                                                                         Console.WriteLine("Log Address:" + log.Address));

            //no contract address

            var filterTransfers = Event <TransferEventDTO> .GetEventABI().CreateFilterInput();

            var ethLogsTokenTransfer = new EthLogsObservableSubscription(client);

            ethLogsTokenTransfer.GetSubscriptionDataResponsesAsObservable().Subscribe(log =>
            {
                try
                {
                    var decoded = Event <TransferEventDTO> .DecodeEvent(log);
                    if (decoded != null)
                    {
                        Console.WriteLine("Contract address: " + log.Address + " Log Transfer from:" + decoded.Event.From);
                    }
                    else
                    {
                        Console.WriteLine("Found not standard transfer log");
                    }
                }
                catch (Exception ex) {
                    Console.WriteLine("Log Address: " + log.Address + " is not a standard transfer log:", ex.Message);
                }
            });



            client.Start().Wait();

            blockHeaderSubscription.SubscribeAsync().Wait();

            blockHeaderSubscription2.SubscribeAsync().Wait();

            pendingTransactionsSubscription.SubscribeAsync().Wait();

            ethGetBalance.SendRequestAsync("0x742d35cc6634c0532925a3b844bc454e4438f44e", BlockParameter.CreateLatest()).Wait();

            ethBlockNumber.SendRequestAsync().Wait();

            ethLogs.SubscribeAsync().Wait();

            ethLogsTokenTransfer.SubscribeAsync(filterTransfers).Wait();

            Thread.Sleep(30000);
            pendingTransactionsSubscription.UnsubscribeAsync().Wait();

            Thread.Sleep(20000);

            blockHeaderSubscription.UnsubscribeAsync().Wait();

            Thread.Sleep(20000);
        }
예제 #9
0
        private static IEnumerator CoroutineUploadSubmission(RoutineContext context)
        {
            // Get accounts
            var requestAccounts = new EthAccountsUnityRequest(mtxNode);

            yield return(requestAccounts.SendRequest());

            var resultsAccounts = requestAccounts.Result;
            var usedAccount     = resultsAccounts[0];

            // Try to create a peer.
            var createPeerFunction = platformContract.GetFunction("createPeer");

            object[] createPeerParams = { };
            var      createPeerInput  = createPeerFunction.CreateTransactionInput(usedAccount, createPeerParams);

            createPeerInput.Gas = new HexBigInteger(3000000);
            var createPeerCall = new EthSendTransactionUnityRequest(mtxNode);

            yield return(createPeerCall.SendRequest(createPeerInput));

            try
            {
                var resultsTransaction = createPeerCall.Result;
            }
            catch (Exception e)
            {
                // Error
                Debug.Log("Could not check peer status");
            }

            // tournament.entryFee();
            var submission = (Submission)((object[])context.param)[0];

            tournamentContract = new Contract(null, tournamentAbi, submission.tournamentAddress);
            var entryFeeFunction = tournamentContract.GetFunction("entryFee");
            var entryFeeInput    = entryFeeFunction.CreateCallInput(new object[0]);

            entryFeeInput.Gas = new HexBigInteger(300000);
            var entryFeeCall = new EthCallUnityRequest(mtxNode);

            yield return(entryFeeCall.SendRequest(entryFeeInput, BlockParameter.CreateLatest()));

            EntryFeeDTO entryFee = new EntryFeeDTO();

            try
            {
                entryFee = entryFeeFunction.DecodeDTOTypeOutput <EntryFeeDTO>(entryFeeCall.Result);
            }
            catch (Exception e)
            {
                Debug.Log("Could not get tournament entry fee.");
            }

            // token.approve(tournament.address, tournament.entryFee)
            if (entryFee.entryFee > 0)
            {
                var      tokenApproveFunction    = tokenContract.GetFunction("approve");
                object[] tokenClearApproveParams = { submission.tournamentAddress, 0 };
                object[] tokenApproveParams      = { submission.tournamentAddress, entryFee.entryFee };
                var      tokenClearApproveInput  = tokenApproveFunction.CreateTransactionInput(usedAccount, tokenClearApproveParams);
                var      tokenApproveInput       = tokenApproveFunction.CreateTransactionInput(usedAccount, tokenApproveParams);
                tokenClearApproveInput.Gas = new HexBigInteger(3000000);
                tokenApproveInput.Gas      = new HexBigInteger(3000000);
                var tokenClearApproveTransaction = new EthSendTransactionUnityRequest(mtxNode);
                var tokenApproveTransaction      = new EthSendTransactionUnityRequest(mtxNode);
                yield return(tokenClearApproveTransaction.SendRequest(tokenClearApproveInput));

                try
                {
                    var tokenClearApprovalResult = tokenClearApproveTransaction.Result;
                }
                catch (Exception e)
                {
                    Debug.Log("Could not approve tournament to withdraw entry fee.");
                }

                yield return(tokenApproveTransaction.SendRequest(tokenApproveInput));

                try
                {
                    var tokenApprovalTransactionResult = tokenApproveTransaction.Result;
                }
                catch (Exception e)
                {
                    Debug.Log("Could not approve tournament to withdraw entry fee.");
                }
            }

            //platform.enterTournament(tournament.address)
            var enterTournamentFunction = platformContract.GetFunction("enterTournament");

            object[] enterTournamentParams = { submission.tournamentAddress };
            var      enterTournamentInput  = enterTournamentFunction.CreateTransactionInput(usedAccount, enterTournamentParams);

            enterTournamentInput.Gas = new HexBigInteger(3300000);
            var enterTournamentTransaction = new EthSendTransactionUnityRequest(mtxNode);

            yield return(enterTournamentTransaction.SendRequest(enterTournamentInput));

            try
            {
                var enterTournamentTransactionResult = enterTournamentTransaction.Result;
            }
            catch (Exception e)
            {
                Debug.Log("Could not enter tournament.");
            }

            // Fix the below code
            // Prepare create submission
            var createSubmissionFunction = tournamentContract.GetFunction("createSubmission");
            // Parse routine params
            var tournamentAddress = (submission.tournamentAddress);
            var title             = submission.title;

            WWWForm form = new WWWForm();

            form.AddBinaryData("description", Encoding.ASCII.GetBytes(((Submission)((object[])(context.param))[0]).title), "description.txt", "text/plain");
            form.AddBinaryData("jsonContent", Encoding.ASCII.GetBytes(((Submission)((object[])(context.param))[0]).body), "jsonContent.json", "application/json");
            UnityWebRequest ipfsRequest = UnityWebRequest.Post(submissionUploadEndpt, form);

            yield return(ipfsRequest.Send());

            print("request completed with code: " + ipfsRequest.responseCode);
            if (ipfsRequest.isError)
            {
                print("Error: " + ipfsRequest.error);
            }
            else
            {
                print("Request Response: " + ipfsRequest.downloadHandler.text);
            }

            var response   = serializer.Deserialize <object>(ipfsRequest.downloadHandler.data) as Dictionary <string, object>;
            var folderHash = Encoding.UTF8.GetBytes((string)response["folderHash"]);

            string[] contributors            = { };
            int[]    contributorDistribution = { };
            string[] references = { };

            if (submission.references != string.Empty)
            {
                references = submission.references.Split(',');
            }
            if (submission.contributors != string.Empty)
            {
                contributors            = submission.contributors.Split(',');
                contributorDistribution = Enumerable.Range(0, contributors.Length).Select(x => 1).ToArray();
            }

            // Make input
            object[] inputParams      = { title, usedAccount, folderHash, contributors, contributorDistribution, references };
            var      transactionInput = createSubmissionFunction.CreateTransactionInput(usedAccount, inputParams);

            transactionInput.Gas      = new HexBigInteger(3000000);
            transactionInput.GasPrice = new HexBigInteger(20);
            // Do request
            var requestTransaction = new EthSendTransactionUnityRequest(mtxNode);

            yield return(requestTransaction.SendRequest(transactionInput));

            // Results
            try
            {
                var resultsTransaction = requestTransaction.Result;
                // Success
                context.done(resultsTransaction);
            }
            catch (Exception e)
            {
                // Error
                Debug.Log("Could not submit submission");
                //Debug.Log(e);
                context.done(null);
            }
        }
예제 #10
0
        static void Main(string[] args)
        {
            var account  = new ManagedAccount("0x12890d2cce102216644c59daE5baed380d84830c", "password");
            var clientws = new WebSocketClient("ws://127.0.0.1:8546");
            var web3ws   = new Web3.Web3(account, clientws);
            var res      = web3ws.Eth.Blocks.GetBlockNumber.SendRequestAsync().Result; //task cancelled exception



            var clientipc = new IpcClient("jsonrpc.ipc");
            var web3ipc   = new Web3.Web3(account, clientipc);
            var resIpc    = web3ws.Eth.Blocks.GetBlockNumber.SendRequestAsync().Result;


            var client = new StreamingWebSocketClient("ws://127.0.0.1:8546");

            client.Error += Client_Error;

            var accountBalanceSubscription = new ParityPubSubObservableSubscription <HexBigInteger>(client);
            var ethBalanceRequest          = new EthGetBalance().BuildRequest("0x12890d2cce102216644c59daE5baed380d84830c", BlockParameter.CreateLatest());

            accountBalanceSubscription.GetSubscriptionDataResponsesAsObservable().Subscribe(newBalance =>
                                                                                            Console.WriteLine("New Balance: " + newBalance.Value.ToString()), onError => Console.WriteLine("Error:" + onError.Message));

            accountBalanceSubscription.GetSubscribeResponseAsObservable()
            .Subscribe(x => Console.WriteLine("SubscriptionId:" + x));


            client.StartAsync().Wait();

            accountBalanceSubscription.SubscribeAsync(ethBalanceRequest).Wait();
            // do transfer

            var web3 = new Web3.Web3(new Account("0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7"));

            for (int i = 0; i < 10; i++)
            {
                web3.Eth.GetEtherTransferService()
                .TransferEtherAndWaitForReceiptAsync("0x12890d2cce102216644c59daE5baed380d848306", 10).Wait();
            }

            client.StopAsync().Wait();

            var accountBalanceSubscription2 = new ParityPubSubObservableSubscription <HexBigInteger>(client);
            var ethBalanceRequest2          = new EthGetBalance().BuildRequest("0x12890d2cce102216644c59daE5baed380d84830c", BlockParameter.CreateLatest());

            accountBalanceSubscription2.GetSubscriptionDataResponsesAsObservable().Subscribe(newBalance =>
                                                                                             Console.WriteLine("New Balance: " + newBalance.Value.ToString()));

            accountBalanceSubscription2.GetSubscribeResponseAsObservable()
            .Subscribe(x => Console.WriteLine("SubscriptionId:" + x));

            client.StartAsync().Wait();

            accountBalanceSubscription2.SubscribeAsync(ethBalanceRequest2).Wait();

            for (int i = 0; i < 10; i++)
            {
                web3.Eth.GetEtherTransferService()
                .TransferEtherAndWaitForReceiptAsync("0x12890d2cce102216644c59daE5baed380d848306", 10).Wait();
            }
        }
        public override Task <string[]> ExecuteAsync(IClient client)
        {
            var ibftGetValidatorsByBlockNumber = new IbftGetValidatorsByBlockNumber(client);

            return(ibftGetValidatorsByBlockNumber.SendRequestAsync(BlockParameter.CreateLatest()));
        }
예제 #12
0
        public async override Task <Order> Run(Order order, CommercePipelineExecutionContext context)
        {
            Condition.Requires(context).IsNotNull($"{this.Name}: The argument can not be null");
            Condition.Requires(order).IsNotNull($"{this.Name}: The argument can not be null");


            var ethPolicy = context.GetPolicy <EthereumClientPolicy>();

            if (ethPolicy == null)
            {
                Logging.Log(context.GetPolicy <KnownResultCodes>().Error, "Ethereum: missing policy configuration.", context);
                return(order);
            }

            // Getting customer id contract
            var contactComponent = order.GetComponent <ContactComponent>();

            if (contactComponent == null || !contactComponent.IsRegistered)
            {
                return(order);
            }
            var getCustomerCommand = new GetCustomerCommand(_getCustomerPipeline, _serviceProvider);
            var customerId         = (contactComponent.CustomerId.ToLower().StartsWith("entity") ? contactComponent.CustomerId : CommerceEntity.IdPrefix <Customer>() + contactComponent.CustomerId);

            if (string.IsNullOrWhiteSpace(customerId))
            {
                return(order);
            }
            var customer = await getCustomerCommand.Process(context.CommerceContext, customerId);

            var customerDetails = customer.GetComponent <CustomerDetailsComponent>();

            if (!(customerDetails.View.ChildViews.Where(v => v.Name.ToLower() == Constants.Pipelines.Views.BlockchainInformationViewName.ToLower()).FirstOrDefault() is EntityView blockchainView))
            {
                return(order);
            }

            var contractIdProperty = blockchainView.Properties.FirstOrDefault(p => p.Name == Constants.Pipelines.Fields.IdentityContractAddressFieldName);

            if (contractIdProperty == null || string.IsNullOrWhiteSpace(contractIdProperty.RawValue?.ToString()))
            {
                return(order);
            }

            var web3 = new Web3(ethPolicy.NodeUrl);

            await Blockchain.UnlockMerchantAccountAsync(web3, context);

            var royaltyContract     = web3.Eth.GetContract(ethPolicy.RoyaltyContractABI, ethPolicy.RoyaltyContractAddress);
            var getAssetUrlFunction = royaltyContract.GetFunction("getAssetUrl");
            var assetPurchaseEvent  = royaltyContract.GetEvent("AssetPurchased");

            var orderLines = order.Lines;

            foreach (var orderLine in orderLines)
            {
                try
                {
                    var token = new CancellationTokenSource();
                    var value = new HexBigInteger(8568000000000000); // the amount equates about $2

                    var product = orderLine.GetComponent <CartProductComponent>();
                    if (product == null)
                    {
                        continue;
                    }

                    if (!product.Tags.Any(t => t.Name == "blockchainroyalty"))
                    {
                        continue;
                    }

                    var producId    = orderLine.GetComponent <CartProductComponent>()?.Id;
                    var gasEstimate = await getAssetUrlFunction.EstimateGasAsync(ethPolicy.MerchantAccountAddress, new HexBigInteger(200000), value, producId, contractIdProperty.RawValue.ToString());

                    var receipt = await getAssetUrlFunction.SendTransactionAndWaitForReceiptAsync(ethPolicy.MerchantAccountAddress, gasEstimate, value, token, producId, contractIdProperty.RawValue.ToString());

                    var filterPurchaser = assetPurchaseEvent.CreateFilterInput(new BlockParameter(receipt.BlockNumber), BlockParameter.CreateLatest());


                    if (((bool)receipt.HasErrors()))
                    {
                        Logging.Log(context.GetPolicy <KnownResultCodes>().Error, $"Ethereum: unable to get receipt for the digital asset token retrieval. Transaction failed with status {receipt.Status}.", context);
                        return(order);
                    }

                    var logs = await assetPurchaseEvent.GetAllChanges <AssetPurchaseEvent>(filterPurchaser);

                    orderLine.SetComponent(new DigitalDownloadBlockchainTokenComponent
                    {
                        BlockchainDownloadToken = logs.Last().Event.Token
                    });
                }
                catch (Exception ex)
                {
                    Logging.Log(context.GetPolicy <KnownResultCodes>().Error, "Ethereum: unable to send transaction getAssetUrl. " + ex.Message, context);
                    return(order);
                }
                Logging.Log(context.GetPolicy <KnownResultCodes>().Information, $"Ethereum: received asset URL token from {ethPolicy.RoyaltyContractAddress}", context);
            }

            return(order);
        }
 public EthGetBalance(IClient client) : base(client, ApiMethods.cfx_getBalance.ToString())
 {
     DefaultBlock = BlockParameter.CreateLatest();
 }
예제 #14
0
 public EthGetStorageAt(RpcClient client) : base(client, ApiMethods.eth_getStorageAt.ToString())
 {
     DefaultBlock = BlockParameter.CreateLatest();
 }
예제 #15
0
        public async Task <CheckModels.CreateCheckEventDTO> CreatedLastCheck(string fromAddress)
        {
            _web3 = _web3 ?? _web3Backend.GetDefaultWeb3();

            _checkcontract = _checkcontract ??
                             await _contracts.GetContract("PostdatedCheckManager",
                                                          _config.GetSection("NetworkId").Value);


            var eventHandler = _web3.Eth.GetEvent <CheckModels.CreateCheckEventDTO>(_checkcontract.Address);
            var filter       = eventHandler.CreateFilterInput(BlockParameter.CreateLatest(), BlockParameter.CreateLatest());
            var results      = await eventHandler.GetAllChanges(filter);

            var lastEvent = results?.First().Event;

            return(lastEvent);
        }
        public async Task Test()
        {
            var web3        = Web3Factory.GetWeb3();
            var addressFrom = AccountFactory.Address;
            var receipt     = await web3.Eth.GetContractDeploymentHandler <TestEventDeployment>()
                              .SendRequestAndWaitForReceiptAsync(new TestEventDeployment()
            {
                FromAddress = addressFrom
            });


            var contractHandler = web3.Eth.GetContractHandler(receipt.ContractAddress);

            var bytes = "0x3031303230333034000000000000000000000000000000000000000000000000".HexToByteArray();

            //Event with all parameters fixed 32 bytes 2 addresses indexed and last indexed bytes 32
            var eventAllBytes32  = contractHandler.GetEvent <PushedResultEventDTO>();
            var filterAllBytes32 = await eventAllBytes32.CreateFilterAsync(addressFrom, addressFrom, bytes,
                                                                           new BlockParameter(receipt.BlockNumber), BlockParameter.CreateLatest());


            //Event with dynamic and last indexed bytes32
            var eventPushed = contractHandler.GetEvent <PushedEventDTO>();

            //ERROR creating filter
            //var filter2 = await eventPushed.CreateFilterAsync(addressFrom, addressFrom, bytes,
            //    new BlockParameter(receipt.BlockNumber), BlockParameter.CreateLatest());

            //Event with dynamic bytes all indexed values at the front
            var eventIndexedAtTheFront  = contractHandler.GetEvent <Pushed2EventDTO>();
            var filterIndexedAtTheFront = await eventIndexedAtTheFront.CreateFilterAsync(addressFrom, addressFrom, bytes,
                                                                                         new BlockParameter(receipt.BlockNumber), BlockParameter.CreateLatest());


            var pushReceipt = await contractHandler.SendRequestAndWaitForReceiptAsync(new PushEventFunction()
            {
                FromAddress = addressFrom
            });

            // Getting changes from the event with all bytes32
            var filterChangesAllBytes32 = await eventAllBytes32.GetFilterChanges <PushedResultEventDTO>(filterAllBytes32);

            Assert.NotEmpty(filterChangesAllBytes32);

            Assert.Equal(addressFrom.ToLower(), filterChangesAllBytes32[0].Event.First.ToLower());

            //Decoding the event (that we cannot create a filter) from the transaction receipt
            var eventsPushed = eventPushed.DecodeAllEventsForEvent <PushedEventDTO>(pushReceipt.Logs);

            Assert.NotEmpty(eventsPushed);

            Assert.Equal(addressFrom.ToLower(), eventsPushed[0].Event.Publisher.ToLower());


            // Getting changes from the event with indexed at the front
            var filterChangesIndexedAtTheFront = await eventIndexedAtTheFront.GetFilterChanges <PushedResultEventDTO>(filterIndexedAtTheFront);

            Assert.NotEmpty(filterChangesIndexedAtTheFront);

            Assert.Equal(addressFrom.ToLower(), filterChangesIndexedAtTheFront[0].Event.First.ToLower());
        }
예제 #17
0
        public override Task <string[]> ExecuteAsync(IClient client)
        {
            var cliqueGetSigners = new CliqueGetSigners(client);

            return(cliqueGetSigners.SendRequestAsync(BlockParameter.CreateLatest()));
        }
예제 #18
0
 public async Task <HexBigInteger> SendRequestAsync(CallInput callInput, object id = null)
 {
     return(await SendRequestAsync(callInput, BlockParameter.CreateLatest(), id));
 }
예제 #19
0
        public override async Task <JObject> ExecuteAsync(IClient client)
        {
            var senderAddress = "0x12890d2cce102216644c59daE5baed380d84830c";
            var privateKey    = "0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7";
            var abi           =
                @"[{""constant"":false,""inputs"":[{""name"":""val"",""type"":""int256""}],""name"":""multiply"",""outputs"":[{""name"":""d"",""type"":""int256""}],""type"":""function""},{""inputs"":[{""name"":""multiplier"",""type"":""int256""}],""type"":""constructor""}]";
            var byteCode =
                "0x60606040526040516020806052833950608060405251600081905550602b8060276000396000f3606060405260e060020a60003504631df4f1448114601a575b005b600054600435026060908152602090f3";

            var multiplier = 7;

            var web3 = new Web3.Web3(new Account(privateKey), client);

            var receipt = await
                          web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync(abi, byteCode, senderAddress,
                                                                                    new HexBigInteger(900000), CancellationToken.None, multiplier);

            var contract = web3.Eth.GetContract(abi, receipt.ContractAddress);

            var function         = contract.GetFunction("multiply");
            var transactionInput = function.CreateTransactionInput(senderAddress, null, null, 7);
            var signer           = new TransactionSigner();
            var nonce            = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(senderAddress);

            var signedTransaction = signer.SignTransaction(privateKey, transactionInput.To, 0, nonce.Value,
                                                           Transaction.DEFAULT_GAS_PRICE, 900000,
                                                           transactionInput.Data);

            var traceTransaction = new TraceRawTransaction(client);

            return(await traceTransaction.SendRequestAsync(signedTransaction.EnsureHexPrefix(),
                                                           new[] { TraceType.vmTrace }, BlockParameter.CreateLatest()));
        }
예제 #20
0
        public async Task <List <ENSHistoryDomain> > GetHistoryByAddressAndTimeFromAsync(SearchParameter searchParameter)
        {
            return(await Task.Run(() =>
            {
                //To connect to infura using .net451 and TLS2 you need to set it in advance
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                //Connection
                var web3 = new Web3(Constants.ETHConnection1);
                var contract = web3.Eth.GetContract(Constants.ABI, searchParameter.Address);

                //get types of event BidRevealed
                var eventBidRevealed = contract.GetEvent("BidRevealed");

                //retrieve latest block info
                var blocksWithTransactionsLatest = web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(BlockParameter.CreateLatest()).Result;
                ulong latestBlock = (ulong)blocksWithTransactionsLatest.Number.Value;
                ulong to = (ulong)blocksWithTransactionsLatest.Timestamp.Value;

                //DateTime lastestDate = UnixTimeStampToDateTime(latestTimeStamp);

                //go back till get from
                ulong fromBlock = latestBlock - 1;
                ulong currentDate;
                List <ENSHistoryDomain> ensHistoryDomains = new List <ENSHistoryDomain>();
                do
                {
                    var blocksWithTransactions = web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(new BlockParameter(fromBlock), new BlockParameter(latestBlock)).Result;
                    currentDate = (ulong)blocksWithTransactions.Timestamp.Value;
                    fromBlock -= 1000;
                } while (searchParameter.From <= currentDate);


                var filterInput = eventBidRevealed.CreateFilterInput(new BlockParameter(fromBlock), BlockParameter.CreateLatest());
                var logs = eventBidRevealed.GetAllChanges <BidRevealedEventDTOBase>(filterInput).Result;

                foreach (var log in logs)
                {
                    //double check date by retrieving the block number from eth api
                    //at the very same time if it is within the range of date then create list to retrun
                    var blocksWithTransactions = web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(new BlockParameter(log.Log.BlockNumber)).Result;
                    currentDate = (ulong)blocksWithTransactions.Timestamp.Value;
                    if (searchParameter.From <= currentDate)
                    {
                        ENSHistoryDomain ensHistory = new ENSHistoryDomain();
                        ensHistory.Address = searchParameter.Address;
                        ensHistory.TimeStamp = (ulong)blocksWithTransactions.Timestamp.Value;
                        ensHistory.BlockHash = blocksWithTransactions.BlockHash;
                        ensHistory.BlockNumber = (ulong)blocksWithTransactions.Number.Value;
                        ensHistory.NumberOfTransactions = blocksWithTransactions.Transactions.Length;
                        ensHistory.Author = blocksWithTransactions.Author;
                        ensHistoryDomains.Add(ensHistory);
                    }
                }

                if (ensHistoryDomains.Count == 0)
                {
                    return new List <ENSHistoryDomain>()
                    {
                        new ENSHistoryDomain()
                        {
                            Address = searchParameter.Address, NumberOfTransactions = -2
                        }
                    };
                }

                return ensHistoryDomains;
            }));
        }
 public EthGetTransactionCount(IClient client) : base(client, ApiMethods.cfx_getTransactionCount.ToString())
 {
     DefaultBlock = BlockParameter.CreateLatest();
 }
예제 #22
0
        public async void TestOriginal()
        {
            var byteCode      = "0x6060604052341561000f57600080fd5b60ac8061001d6000396000f300606060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416635170a9d081146043575b600080fd5b3415604d57600080fd5b6053607c565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b33905600a165627a7a72305820ad71c73577f8423259abb92d0e9aad1a0e98ef0c93a1a1aeee4c4407c9b85c320029";
            var abi           = @"[ { ""constant"": true, ""inputs"": [], ""name"": ""returnSender"", ""outputs"": [ { ""name"": """", ""type"": ""address"", ""value"": ""0x108b08336f8890a3f5d091b1f696c67b13b19c4d"" } ], ""payable"": false, ""stateMutability"": ""view"", ""type"": ""function"" } ]";
            var senderAddress = AccountFactory.Address;
            var web3          = Web3Factory.GetWeb3();

            var receipt = await web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync(abi, byteCode, senderAddress, new HexBigInteger(900000));

            var contractAddress = receipt.ContractAddress;
            var contract        = web3.Eth.GetContract(abi, contractAddress);
            var function        = contract.GetFunction("returnSender");
            var returnAddress   = await function.CallAsync <string>(senderAddress, new HexBigInteger(900000), null, BlockParameter.CreateLatest());

            Assert.Equal(senderAddress.ToLower(), returnAddress.ToLower());
        }