Skip to content

Commit

Permalink
chore: fix logging & symbol name pulling & perc logging
Browse files Browse the repository at this point in the history
  • Loading branch information
JayArrowz committed Aug 31, 2021
1 parent e711579 commit 5cfa19f
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 20 deletions.
2 changes: 2 additions & 0 deletions Models/PairCreatedEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ public class PairCreatedEvent

[Parameter("uint256", "", 4, false)]
public BigInteger Amount { get; set; }

public string Symbol { get; set; }
}
}
17 changes: 12 additions & 5 deletions RugChecker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,18 @@ public RugChecker(IOptions<SniperConfiguration> sniperConfig, IHttpClientFactory
_pairContractStr = File.ReadAllText("./Abis/Pair.json");
}

public async Task<string> GetSymbol(PairCreatedEvent pairCreatedEvent)
{
var otherPairAddress = pairCreatedEvent.Token0.Equals(_sniperConfig.LiquidityPairAddress, StringComparison.InvariantCultureIgnoreCase) ?
pairCreatedEvent.Token1 : pairCreatedEvent.Token0;
return await _bscWeb3.Eth.GetContract(_erc20Abi, otherPairAddress).GetFunction("symbol").CallAsync<string>();
}

public async Task<bool> CheckRugAsync(PairCreatedEvent pairCreatedEvent)
{
if (pairCreatedEvent.Token0 != _sniperConfig.LiquidityPairAddress && pairCreatedEvent.Token1 != _sniperConfig.LiquidityPairAddress)
{
Serilog.Log.Logger.Information("Target liquidity pair found for pair: {0} - {1}. Not bought", pairCreatedEvent.Token0, pairCreatedEvent.Token0);
Serilog.Log.Logger.Warning("Target liquidity pair found for pair: {0} - {1}. Not bought", pairCreatedEvent.Token0, pairCreatedEvent.Token0);
return false;
}

Expand All @@ -61,7 +68,7 @@ private async Task<bool> CheckMinLiquidity(PairCreatedEvent pairCreatedEvent, st
var amountStr = Web3.Convert.FromWei(totalAmount).ToString();
if (!result)
{
Serilog.Log.Logger.Information("Not enough liquidity added to token {0}. Not buying. Only {1} liquidity added", pair, amountStr);
Serilog.Log.Logger.Warning("Not enough liquidity added to token {0}. Not buying. Only {1} liquidity added", pair, amountStr);
return result;
}
else
Expand All @@ -75,7 +82,7 @@ private async Task<bool> CheckMinLiquidity(PairCreatedEvent pairCreatedEvent, st
var totalTokenAmount = await _bscWeb3.Eth.GetContract(_erc20Abi, pairCreatedEvent.Pair).GetFunction("totalSupply").CallAsync<BigInteger>();
var percentageInPool = new Fraction(tokenAmountInPool).Divide(totalTokenAmount).Multiply(100);
result = ((decimal)percentageInPool) > _sniperConfig.MinimumPercentageOfTokenInLiquidityPool;
Serilog.Log.Logger.Information("Token {0} Token Amount in Pool: {1} Total Supply: {2} Total Percentage in pool: {3}% Min Percentage Liquidity Check Status: {4}", pairCreatedEvent.Pair, tokenAmountInPool, totalTokenAmount, percentageInPool, result);
Serilog.Log.Logger.Information("Token {0} Token Amount in Pool: {1} Total Supply: {2} Total Percentage in pool: {3}% Min Percentage Liquidity Check Status: {4}", pairCreatedEvent.Pair, tokenAmountInPool, totalTokenAmount, percentageInPool.ToDouble(), result);
}
return result;
}
Expand All @@ -93,7 +100,7 @@ public async Task<bool> CheckContractVerified(string otherTokenAddress)
var innerResult = jObject["result"][0];
if (innerResult["ABI"].Value<string>() == "Contract source code not verified")
{
Serilog.Log.Logger.Information("Bsc contract is not verified for token {0}", otherTokenAddress);
Serilog.Log.Logger.Warning("Bsc contract is not verified for token {0}", otherTokenAddress);
return false;
}

Expand All @@ -106,7 +113,7 @@ public async Task<bool> CheckContractVerified(string otherTokenAddress)
var containsRugCheckStrings = _sniperConfig.ContractRugCheckStrings.FirstOrDefault(t => innerResult["SourceCode"].Contains(t));
if (!string.IsNullOrEmpty(containsRugCheckStrings))
{
Serilog.Log.Logger.Information("Failed rug check for token {0}, contains string: {1}", otherTokenAddress, containsRugCheckStrings);
Serilog.Log.Logger.Warning("Failed rug check for token {0}, contains string: {1}", otherTokenAddress, containsRugCheckStrings);
return false;
}

Expand Down
15 changes: 8 additions & 7 deletions SniperService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ private async Task ReadLogs(IWeb3 web3, Contract contract, Action<EventLog<PairC
new HexBigInteger(BigInteger.Subtract(newBlockNumber.Value, new BigInteger(1)))
: (isBehind ? currentProcessedBlock : newBlockNumber);

Log.Logger.Information("Reading Logs from Block: {fromBlockNumber} to {newBlockNumber}, Contract address: {Address}", fromBlockNumber, newBlockNumber, contract.Address);
Log.Logger.Information("Reading Logs from Block: {fromBlockNumber} to {newBlockNumber}", fromBlockNumber, newBlockNumber);
onBlockUpdate.Invoke(newBlockNumber);
try
{
Expand All @@ -67,14 +67,14 @@ await processor.ExecuteAsync(startAtBlockNumberIfNotProcessed: fromBlockNumber,
Serilog.Log.Logger.Error("Error processing block", e);
}

Log.Logger.Information("Processed: {fromBlockNumber} to {newBlockNumber}, Contract address: {Address}", fromBlockNumber, newBlockNumber, contract.Address);
Log.Logger.Debug("Processed: {fromBlockNumber} to {newBlockNumber}, Contract address: {Address}", fromBlockNumber, newBlockNumber, contract.Address);

}

private void CreateTokenPair(FilterLog log, Action<EventLog<PairCreatedEvent>> onNext)
{
var pairCreated = log.DecodeEvent<PairCreatedEvent>();
Log.Logger.Information("Pair Created Event: {@log} Data: {@pairCreated}", log, pairCreated);
Log.Logger.Information("Pair Created Event Found: {@log} Data: {@pairCreated}", log, pairCreated);
if (onNext != null)
{
onNext.Invoke(pairCreated);
Expand Down Expand Up @@ -108,16 +108,17 @@ void UpdateBscBlock(HexBigInteger newBscBlock)
private async Task PairCreated(EventLog<PairCreatedEvent> pairCreated)
{
var pair = pairCreated.Event;
var symbol = await _rugChecker.GetSymbol(pair);
pair.Symbol = symbol;
var rugCheckPassed = _sniperConfig.RugCheckEnabled ? await _rugChecker.CheckRugAsync(pair) : true;
var otherPairAddress = pair.Token0.Equals(_sniperConfig.LiquidityPairAddress, StringComparison.InvariantCultureIgnoreCase) ? pair.Token1 : pair.Token0;
var otherTokenIdx = pair.Token0.Equals(_sniperConfig.LiquidityPairAddress, StringComparison.InvariantCultureIgnoreCase) ? 1 : 0;

Log.Logger.Information("Rug Checked Pair: {0} - {1} Result: {2}", pair.Token0, pair.Token1, rugCheckPassed);

Log.Logger.Information("Discovered Token Pair {0} Rug check Result: {1}", symbol, rugCheckPassed);
if (rugCheckPassed)
{
Log.Logger.Information("Buying Token pair: {0} : {1}", pair.Token0, pair.Token1);
await _tradeHandler.Buy(otherPairAddress, otherTokenIdx, pair.Pair);
Log.Logger.Information("Buying Token pair: {0}", symbol);
await _tradeHandler.Buy(otherPairAddress, otherTokenIdx, pair.Pair, _sniperConfig.AmountToSnipe);
}
}

Expand Down
15 changes: 11 additions & 4 deletions TradeHandler.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using BscTokenSniper.Models;
using Fractions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Nethereum.Contracts;
using Nethereum.Hex.HexTypes;
Expand All @@ -18,13 +19,14 @@

namespace BscTokenSniper
{
public class TradeHandler
public class TradeHandler : IDisposable
{
private readonly SniperConfiguration _sniperConfig;
private readonly Web3 _bscWeb3;
private readonly Contract _pancakeContract;
private readonly RugChecker _rugChecker;
private List<TokensOwned> _ownedTokenList = new();
private bool _stopped;
private readonly string _erc20Abi;

public TradeHandler(IOptions<SniperConfiguration> options, RugChecker rugChecker)
Expand All @@ -38,13 +40,13 @@ public TradeHandler(IOptions<SniperConfiguration> options, RugChecker rugChecker
Start();
}

public async Task Buy(string tokenAddress, int tokenIdx, string pairAddress)
public async Task Buy(string tokenAddress, int tokenIdx, string pairAddress, double amt)
{
try
{
var buyFunction = _pancakeContract.GetFunction("swapExactETHForTokens");
var gas = new HexBigInteger(_sniperConfig.GasAmount);
var amount = new HexBigInteger(Web3.Convert.ToWei(_sniperConfig.AmountToSnipe));
var amount = new HexBigInteger(Web3.Convert.ToWei(amt));
var buyReturnValue = await buyFunction.SendTransactionAsync(_sniperConfig.WalletAddress, gas, amount, 0,
new string[] { _sniperConfig.LiquidityPairAddress, tokenAddress },
_sniperConfig.WalletAddress,
Expand Down Expand Up @@ -118,7 +120,7 @@ public void Start()

private void MonitorPrices()
{
while (true)
while (!_stopped)
{
for (int i = _ownedTokenList.Count - 1; i >= 0; i--)
{
Expand All @@ -137,5 +139,10 @@ private void MonitorPrices()
Thread.Sleep(TimeSpan.FromSeconds(5));
}
}

public void Dispose()
{
_stopped = true;
}
}
}
8 changes: 4 additions & 4 deletions appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": "Information",
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{ "Name": "Console" },
{
Expand All @@ -22,9 +22,8 @@
}
},
"SniperConfiguration": {
"BscScanApiKey": "xxx",
"WalletPrivateKey": "xxx",
"WalletAddress": "xxx",
"WalletPrivateKey": "xxx",
"PancakeswapFactoryAddress": "0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73",
"LiquidityPairAddress": "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",
"PancakeswapRouterAddress": "0x10ED43C718714eb63d5aA57B78B54704E256024E",
Expand All @@ -35,6 +34,7 @@
"GasAmount": 300000,
"BscHttpApi": "https://speedy-nodes-nyc.moralis.io/xxx/bsc/mainnet",
"BscNode": "wss://speedy-nodes-nyc.moralis.io/xxx/bsc/mainnet/ws",
"BscScanApiKey": "xxx",
"MinLiquidityAmount": 0.7,
"MinimumPercentageOfTokenInLiquidityPool": 95,
"RugCheckEnabled": true,
Expand Down

0 comments on commit 5cfa19f

Please sign in to comment.