cs-codex-dist-tests/Framework/NethereumWorkflow/Web3Wrapper.cs

47 lines
1.3 KiB
C#
Raw Normal View History

2024-03-21 11:18:04 +00:00
using Logging;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.Web3;
using Utils;
namespace NethereumWorkflow
{
public interface IWeb3Blocks
{
2024-03-21 15:11:28 +00:00
ulong GetCurrentBlockNumber();
DateTime? GetTimestampForBlock(ulong blockNumber);
2024-03-21 11:18:04 +00:00
}
public class Web3Wrapper : IWeb3Blocks
{
private readonly Web3 web3;
private readonly ILog log;
public Web3Wrapper(Web3 web3, ILog log)
{
this.web3 = web3;
this.log = log;
}
2024-03-21 15:11:28 +00:00
public ulong GetCurrentBlockNumber()
2024-03-21 11:18:04 +00:00
{
var number = Time.Wait(web3.Eth.Blocks.GetBlockNumber.SendRequestAsync());
2024-03-21 15:11:28 +00:00
return Convert.ToUInt64(number.ToDecimal());
2024-03-21 11:18:04 +00:00
}
2024-03-21 15:11:28 +00:00
public DateTime? GetTimestampForBlock(ulong blockNumber)
2024-03-21 11:18:04 +00:00
{
try
{
2024-03-21 15:11:28 +00:00
var block = Time.Wait(web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(new BlockParameter(blockNumber)));
2024-03-21 11:18:04 +00:00
if (block == null) return null;
return DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(block.Timestamp.ToDecimal())).UtcDateTime;
}
catch (Exception ex)
{
log.Error("Exception while getting timestamp for block: " + ex);
return null;
}
}
}
}