예제 #1
0
        public static async Task SubscribeAndRunAsync()
        {
            if (client == null)
            {
                client        = new StreamingWebSocketClient("wss://mainnet.infura.io/ws/v3/206cfadcef274b49a3a15c45c285211c");
                client.Error += Client_Error;
            }
            // 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)
                                                                                         , exception =>
            {
                Console.WriteLine("BlockHeaderSubscription error info:" + exception.Message);
            });

            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)
                                                                                                 , exception =>
            {
                Console.WriteLine("Pending transactions error info:" + exception.Message);
            });

            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)
                                                                         , exception =>
            {
                Console.WriteLine("Logs error info:" + exception.Message);
            });

            //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);
                }
            }, exception =>
            {
                Console.WriteLine("Logs error info:" + exception.Message);
            });



            await client.StartAsync();

            blockHeaderSubscription.SubscribeAsync().Wait();

            //blockHeaderSubscription2.SubscribeAsync().Wait();

            pendingTransactionsSubscription.SubscribeAsync().Wait();

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

            //ethBlockNumber.SendRequestAsync().Wait();

            //ethLogs.SubscribeAsync().Wait();

            //await ethLogsTokenTransfer.SubscribeAsync(filterTransfers);

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

            //Thread.Sleep(20000);

            //blockHeaderSubscription.UnsubscribeAsync().Wait();



            // await client.StopAsync();
            // await SubscribeAndRunAsync();
        }
예제 #2
0
        public static async Task SubscribeTosync() //Emitted each time reserves are updated via mint, burn, swap, or sync. https://uniswap.org/docs/v2/smart-contracts/pair/
        {
            string uniSwapFactoryAddress = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f";

            var web3 = new Web3.Web3("https://mainnet.infura.io/v3/7238211010344719ad14a89db874158c");


            string daiAddress  = "0x6b175474e89094c44da98b954eedeac495271d0f";
            string wethAddress = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";

            var pairContractAddress = await web3.Eth.GetContractQueryHandler <GetPairFunction>()
                                      .QueryAsync <string>(uniSwapFactoryAddress,
                                                           new GetPairFunction()
            {
                TokenA = daiAddress, TokenB = wethAddress
            });

            var filter = Event <PairSyncEventDTO> .GetEventABI()
                         .CreateFilterInput(new[] { pairContractAddress });

            using (var client = new StreamingWebSocketClient("wss://mainnet.infura.io/ws/v3/7238211010344719ad14a89db874158c"))
            {
                var subscription = new EthLogsObservableSubscription(client);
                subscription.GetSubscriptionDataResponsesAsObservable().
                Subscribe(log =>
                {
                    try
                    {
                        EventLog <PairSyncEventDTO> decoded = Event <PairSyncEventDTO> .DecodeEvent(log);
                        if (decoded != null)
                        {
                            decimal reserve0 = Web3.Web3.Convert.FromWei(decoded.Event.Reserve0);
                            decimal reserve1 = Web3.Web3.Convert.FromWei(decoded.Event.Reserve1);
                            Console.WriteLine($@"Price={reserve0 / reserve1}");
                        }
                        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);
                    }
                });

                await client.StartAsync();

                subscription.GetSubscribeResponseAsObservable().Subscribe(id => Console.WriteLine($"Subscribed with id: {id}"));
                await subscription.SubscribeAsync(filter);

                while (true) //pinging to keep alive infura
                {
                    var handler = new EthBlockNumberObservableHandler(client);
                    handler.GetResponseAsObservable().Subscribe(x => Console.WriteLine(x.Value));
                    await handler.SendRequestAsync();

                    Thread.Sleep(30000);
                }
            }
        }
예제 #3
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);
            };

            var disposable = Observable.FromEventPattern <StreamingEventArgs <Block> >(h => blockHeaderSubscription2.SubscriptionDataResponse += h,
                                                                                       h => blockHeaderSubscription2.SubscriptionDataResponse -= h).Subscribe(x =>
                                                                                                                                                              Console.WriteLine("New Block from observable from event : " + x.EventArgs.Response.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);
        }
예제 #4
0
        private static async Task <bool> Run(int blockchainID, string webSocketsUrl, string rpcUrl, BlockchainType blockchainType,
                                             BlockchainNetwork blockchainNetwork)
        {
            bool hasFailed = false;

            using (var client = new StreamingWebSocketClient(webSocketsUrl))
            {
                EthLogsObservableSubscription logsSubscription = new EthLogsObservableSubscription(client);

                Web3 cl = new Web3(rpcUrl);

                RequestInterceptor r = new RPCInterceptor(blockchainType);
                cl.Client.OverridingRequestInterceptor = r;
                EthApiService eth = new EthApiService(cl.Client);

                logsSubscription.GetSubscriptionDataResponsesAsObservable().Subscribe(async filterLog =>
                {
                    FilterLog transaction = filterLog;

                    if (transaction.Removed)
                    {
                        return;
                    }

                    if (SmartContractManager.TryGetAddress(blockchainID, filterLog.Address, out ContractTypeEnum type))
                    {
                        await ProcessSmartContractEvent(blockchainID, blockchainType, blockchainNetwork, type, eth, filterLog,
                                                        transaction, cl);
                    }
                });

                _dictionary[blockchainID] = new Subscription(client, logsSubscription);

                await client.StartAsync();

                client.Error += Client_Error;

                while (!client.IsStarted)
                {
                    await Task.Delay(1000);
                }

                await logsSubscription.SubscribeAsync();

                while (!hasFailed)
                {
                    try
                    {
                        var handler = new EthBlockNumberObservableHandler(client);
                        handler.GetResponseAsObservable().Subscribe(integer => { });
                        await handler.SendRequestAsync();

                        SystemStatus status = new SystemStatus(TaskNames.WebSockets, blockchainID);
                        await using (var connection = new MySqlConnection(OTHubSettings.Instance.MariaDB.ConnectionString))
                        {
                            await status.InsertOrUpdate(connection, true, null, false, "Blockchain Sync");
                        }
                    }

                    catch (Exception ex) when(errorCounter <= 100)
                    {
                        hasFailed = true;
                        _dictionary.Remove(blockchainID, out _);
                        client.Dispose();
                        //try
                        //{
                        //    await client.StopAsync();
                        //    await client.StartAsync();
                        //}
                        //catch (Exception)
                        //{
                        //    Logger.WriteLine(Source.BlockchainSync, ex.ToString());
                        //}
                    }

                    await Task.Delay(120000);
                }
            }

            return(!hasFailed);
        }