/ Framework / NethereumWorkflow / Web3Wrapper.cs
Web3Wrapper.cs
 1  using BlockchainUtils;
 2  using Logging;
 3  using Nethereum.RPC.Eth.DTOs;
 4  using Nethereum.Web3;
 5  using Utils;
 6  
 7  namespace NethereumWorkflow
 8  {
 9      public class Web3Wrapper : IWeb3Blocks
10      {
11          private readonly Web3 web3;
12          private readonly ILog log;
13  
14          public Web3Wrapper(Web3 web3, ILog log)
15          {
16              this.web3 = web3;
17              this.log = log;
18          }
19  
20          public ulong GetCurrentBlockNumber()
21          {
22              return Retry(() =>
23              {
24                  var number = Time.Wait(web3.Eth.Blocks.GetBlockNumber.SendRequestAsync());
25                  return Convert.ToUInt64(number.ToDecimal());
26              });
27          }
28  
29          public DateTime? GetTimestampForBlock(ulong blockNumber)
30          {
31              return Retry<DateTime?>(() =>
32              {
33                  try
34                  {
35                      var block = Time.Wait(web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(new BlockParameter(blockNumber)));
36                      if (block == null) return null;
37                      return DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(block.Timestamp.ToDecimal())).UtcDateTime;
38                  }
39                  catch (Exception ex)
40                  {
41                      log.Error("Exception while getting timestamp for block: " + ex);
42                      return null;
43                  }
44              });
45          }
46  
47          private T Retry<T>(Func<T> action)
48          {
49              var retry = new Retry(nameof(Web3Wrapper),
50                  maxTimeout: TimeSpan.FromSeconds(30),
51                  sleepAfterFail: TimeSpan.FromSeconds(3),
52                  onFail: f => { },
53                  failFast: false);
54  
55              return retry.Run(action);
56          }
57      }
58  }