public static async Task Main() { //DAI contract address var contractAddress = "0x6b175474e89094c44da98b954eedeac495271d0f"; using (var client = new StreamingWebSocketClient("wss://mainnet.infura.io/ws/v3/7238211010344719ad14a89db874158c")) { try { var eventSubscription = new EthLogsObservableSubscription(client); eventSubscription.GetSubscriptionDataResponsesAsObservable().Subscribe(log => { var transfer = log.DecodeEvent <TransferEventDTO>(); Console.WriteLine($@"{transfer.Log.TransactionHash}, From:{transfer.Event.From}, To:{transfer.Event.To}, Value:{Web3.Convert.FromWei(transfer.Event.Value)}"); }); eventSubscription.GetSubscribeResponseAsObservable().Subscribe(id => Console.WriteLine($"Subscribed with id: {id}")); var filterAuction = Event <TransferEventDTO> .GetEventABI().CreateFilterInput(contractAddress); await client.StartAsync(); await eventSubscription.SubscribeAsync(filterAuction); Console.ReadLine(); await eventSubscription.UnsubscribeAsync(); } catch (Exception e) { Console.WriteLine(e.Message); } } }
public static async Task SubscribeToSwaps() //https://uniswap.org/docs/v2/smart-contracts/pair/ Emitted each time a swap occurs via swap. { var token0 = "DAI"; var token1 = "ETH"; var pairContractAddress = "0xa478c2975ab1ea89e8196811f51a7b7ade33eb11"; using (var client = new StreamingWebSocketClient("wss://mainnet.infura.io/ws/v3/7238211010344719ad14a89db874158c")) { Console.WriteLine($"Uniswap trades for {token0} and {token1}"); try { var eventSubscription = new EthLogsObservableSubscription(client); eventSubscription.GetSubscriptionDataResponsesAsObservable().Subscribe(log => { var swap = log.DecodeEvent <SwapEventDTO>(); var amount0Out = Web3.Web3.Convert.FromWei(swap.Event.Amount0Out); var amount1In = Web3.Web3.Convert.FromWei(swap.Event.Amount1In); var amount0In = Web3.Web3.Convert.FromWei(swap.Event.Amount0In); var amount1Out = Web3.Web3.Convert.FromWei(swap.Event.Amount1Out); if (swap.Event.Amount0In == 0 && swap.Event.Amount1Out == 0) { var price = amount0Out / amount1In; var quantity = amount1In; Console.WriteLine($"Sell {token1} Price: {price.ToString("F4")} Quantity: {quantity.ToString("F4")}, From: {swap.Event.To} Block: {swap.Log.BlockNumber}"); } else { var price = amount0In / amount1Out; var quantity = amount1Out; Console.WriteLine($"Buy {token1} Price: {price.ToString("F4")} Quantity: {quantity.ToString("F4")}, From: {swap.Event.To} Block: {swap.Log.BlockNumber}"); } } ); eventSubscription.GetSubscribeResponseAsObservable().Subscribe(id => Console.WriteLine($"Subscribed with id: {id}")); var filterAuction = Event <SwapEventDTO> .GetEventABI().CreateFilterInput(pairContractAddress); await client.StartAsync(); await eventSubscription.SubscribeAsync(filterAuction); Console.ReadLine(); await eventSubscription.UnsubscribeAsync(); } catch (Exception e) { Console.WriteLine(e.Message); } } }
static void Subscribe() { _streamingWebSocketClient.StartAsync().Wait(); PendingTransactionsSubscription.SubscribeAsync().Wait(); Console.WriteLine($"Eth WebSocketsStreamingSample Subscribe ............."); }
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); } } }
static void Main(string[] args) { var client2 = new WebSocketClient("wss://mainnet.infura.io/ws/v3/7238211010344719ad14a89db874158c"); var block1 = new Nethereum.RPC.Eth.Blocks.EthGetBlockWithTransactionsByNumber(client2).SendRequestAsync(new HexBigInteger(10613813)).Result; var block2 = new Nethereum.RPC.Eth.Blocks.EthGetBlockWithTransactionsByNumber(client2).SendRequestAsync(new HexBigInteger(10613813)).Result; var client = new StreamingWebSocketClient("wss://mainnet.infura.io/ws/v3/7238211010344719ad14a89db874158c"); // 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.StartAsync().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); Console.ReadLine(); }
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); }
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(); } }