static void Main(string[] args) { //var device = FirebaseGateway.GetDevice("duzgt9Ubnxo:APA91bEYuVNGByPeAo292pIADQzOjTSA49Ly0ZKQ37INJdENTId1pn8HDHtAXQ3krRmoIEHIRaAvkIsYxADT0MGyZm58fQZGVebZz5DiUFRNLIAGd_mGR7XGnoVqGvqyjJBVAMucXaWw"); //FirebaseGateway.UpdateDevice(device); ////device.addresses_v2.p0.tokens = new System.Collections.Generic.List<Token>() { new Token() {token = "TAP", contractAddress = "cxc0b5b52c9f8b4251a47e91dda3bd61e5512cd782" } }; //ProcessDeviceAddress(device, device.addresses_v2.p0); //foreach (var token in device.addresses_v2.p0.tokens.AsEnumerator()) //{ // ProcessDeviceToken(device, device.addresses_v2.p0, token); //} Console.WriteLine("[MAIN] STARTING APPLICATION TIMER v2.11"); timer.Elapsed += Timer_Elapsed; timer.Interval = timerInterval * 1000; timer.Start(); timerPrep.Elapsed += TimerPrep_Elapsed; timerPrep.Interval = timerPrepInterval * 1000; timerPrep.Start(); AllPReps = IconGateway.GetAllPReps(); while (true) { System.Threading.Thread.Sleep(1000); } }
private static void Timer_Elapsed(object sender, ElapsedEventArgs e) { timer.Stop(); try { Console.WriteLine($"TIMER BLOCK START (Threads {Process.GetCurrentProcess().Threads.Count})"); var lastBlock = IconGateway.GetLastBlock(); if (lastBlock.Height % 10 == 0) { var incompleteBlocks = FirebaseGateway.GetAllIncompleteBlocks(); foreach (var block in incompleteBlocks) { ProcessBlockInThread(block.height); } } if (lastProcessedHeight == 0) { ProcessBlockInThread(lastBlock); } else if (lastProcessedHeight == lastBlock.Height) { //Do nothing } else if (lastProcessedHeight == lastBlock.Height - 1) { ProcessBlockInThread(lastBlock); } else { //We have missed some blocks, need to catch up for (long indexHeight = lastProcessedHeight + 1; indexHeight < lastBlock.Height; indexHeight++) { FirebaseGateway.SetBlockProcessed(new BlockProcessedStatus() { completed = false, height = indexHeight, retryAttempts = -1 }); ProcessBlockInThread(indexHeight); lastProcessedHeight = indexHeight; } ProcessBlockInThread(lastBlock); } lastProcessedHeight = lastBlock.Height; } catch (Exception ex) { //Do nothing for now, next timer hit will retry } finally { timer.Start(); } }
private static void TimerPrep_Elapsed(object sender, ElapsedEventArgs e) { timerPrep.Stop(); try { Console.WriteLine("[MAIN] PREP TIMER ELAPSED, Checking all PReps"); AllPReps = IconGateway.GetAllPReps(); Console.WriteLine($"[MAIN] Retrieved {AllPReps.Preps.Count} P-Reps"); } finally { timerPrep.Start(); } }
public static void ProcessDeviceToken(DeviceRegistration device, Address address, Token token) { SendResponse sendResponse = null; if (address.enablePushDeposits == true && token.isSelected == true) { try { var balance = IconGateway.GetBalance(address, token); if (string.IsNullOrEmpty(token.lastBalance)) { //Store current balance without sending a notification token.lastBalance = balance.ToString(); } else if (token.balanceAsDecimal < balance && balance - token.balanceAsDecimal > 0.005M) //Otherwise user gets a message of receiving 0 { decimal depositReceived = balance - token.balanceAsDecimal; if (string.IsNullOrEmpty(address.Name)) { sendResponse = FirebaseGateway.SendPush(device.token, token.token, $"{token.token} Deposit Received", $"You have received a deposit of {depositReceived.ToString("0.##")} {token.token}"); } else { sendResponse = FirebaseGateway.SendPush(device.token, token.token, $"{token.token} Deposit Received", $"{address.Name.ToUpper()} has received a deposit of {depositReceived.ToString("0.##")} {token.token}"); } //Now update firestore so we dont send the user duplicate messages token.lastBalance = balance.ToString(); token.lastDepositPushSentDate = DateTime.UtcNow; pushNotificationCount++; } else if (token.balanceAsDecimal > balance) { token.lastBalance = balance.ToString(); } } catch (Exception ex) { Console.WriteLine($"[MAIN] EXCEPTION processing Deposit check {ex.Message}"); } } if (sendResponse != null && sendResponse.failure > 0) { if (sendResponse.results.Any(a => a.error == "NotRegistered")) { //This token has become stale, need to remove it from firestore FirebaseGateway.DeleteDevice(device); } } }
public static void ProcessDeviceAddress(DeviceRegistration device, Address address) { SendResponse sendResponse = null; if (!device.registrationDate.HasValue) { device.registrationDate = DateTime.UtcNow; } if (device.enablePushIScoreChange == true) { try { var totalRewards = IconGateway.GetAvailableRewards(address); if (totalRewards > 0) { if (string.IsNullOrEmpty(address.Name)) { sendResponse = FirebaseGateway.SendPush(device.token, address.address, $"{address.Symbol} Rewards Available", $"Congratulations! your reward of {totalRewards.ToString("0.##")} {address.Symbol} is ready to be claimed"); } else { sendResponse = FirebaseGateway.SendPush(device.token, address.address, $"{address.Symbol} Rewards Available", $"Congratulations! your reward of {totalRewards.ToString("0.##")} {address.Symbol} is ready to be claimed from {address.Name.ToUpper()}"); } //Now update firestore so we dont send the user duplicate messages address.availableRewards = totalRewards.ToString(); address.lastIScorePushSentDate = DateTime.UtcNow; } else if (address.availableRewardsAsDecimal > totalRewards) { address.availableRewards = totalRewards.ToString(); } } catch (Exception ex) { Console.WriteLine($"[MAIN] EXCEPTION processing IScore check {ex.Message}"); } } if (sendResponse != null && sendResponse.failure > 0) { if (sendResponse.results.Any(a => a.error == "NotRegistered")) { //This token has become stale, need to remove it from firestore FirebaseGateway.DeleteDevice(device); } } }
static void Main(string[] args) { var icxBlock = IconGateway.GetBlockByHeight(17699880); //ICX dividends var trx = icxBlock.ConfirmedTransactionList[1]; var txResult = IconGateway.GetTransactionResult(trx.TxHash); trx.TxResultDetails = txResult; var msgStr = JsonConvert.SerializeObject(trx); var func = new TokenDepositReceivedFunction.Function(); func.ProcessRecordAsync(null, msgStr).Wait(); }
public async Task ProcessRecordAsync(ILambdaContext context, string message) { context.Logger.LogLine($"[{DateTime.Now.ToString()}] Processed record {message}"); ConfirmedTransaction tx = JsonConvert.DeserializeObject <ConfirmedTransaction>(message); string address; decimal amount; //Subscription to AWS Topic ICX_Transfer //Just triggered from normal ICX to ICX wallets if (tx.From != null && tx.From.StartsWith("hx") && tx.To != null && tx.To.StartsWith("hx")) { address = tx.To; amount = tx.GetIcxValue(); ProcessAddress(context, address, amount); } //Subscription to AWS Topic ICX_Contract_Method //Looks for specific events that causes ICX to be transferred if (tx.TxResultDetails != null) { foreach (var eventItem in tx.TxResultDetails.EventLogs) { if (eventItem.Indexed[0].StartsWith("ICXTransfer")) { address = eventItem.Indexed[2]; amount = IconGateway.GetIcxValueFromHex(eventItem.Indexed[3]); ProcessAddress(context, address, amount); } if (eventItem.Indexed[0].StartsWith("IScoreClaimed")) { address = tx.From; amount = IconGateway.GetIcxValueFromHex(eventItem.Data[0]); amount = amount / 1000M; ProcessAddress(context, address, amount); } } } await Task.CompletedTask; }
public void ProcessDeviceAddress(DeviceRegistration device, Address address, decimal amount) { SendResponse sendResponse = null; if (!device.registrationDate.HasValue) { device.registrationDate = DateTime.UtcNow; } if (address.enablePushDeposits == true) { try { if (string.IsNullOrEmpty(address.Name)) { sendResponse = FirebaseGateway.SendPush(device.token, address.address, $"{address.Symbol} Deposit Received", $"You have received a deposit of {amount.ToString("0.##")} {address.Symbol}"); } else { sendResponse = FirebaseGateway.SendPush(device.token, address.address, $"{address.Symbol} Deposit Received", $"{address.Name.ToUpper()} has received a deposit of {amount.ToString("0.##")} {address.Symbol}"); } address.lastDepositPushSentDate = DateTime.UtcNow; //This will not always be required address.balance = IconGateway.GetBalance(address).ToString(); } catch (Exception ex) { Console.WriteLine($"[MAIN] EXCEPTION processing Deposit check {ex.Message}"); } } if (sendResponse != null && sendResponse.failure > 0) { if (sendResponse.results.Any(a => a.error == "NotRegistered")) { //This token has become stale, need to remove it from firestore FirebaseGateway.DeleteDevice(device); } } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); //var trxScoreSample = File.ReadAllText("TrxScoreSample.json"); //var trxTransferSample = File.ReadAllText("TrxTransferSample.json"); //var trxTransferSampleError = File.ReadAllText("TrxTransferSampleError.json"); //var icxBlock = IconGateway.GetBlockByHeight(17305133); //Normal transfer var icxBlock = IconGateway.GetBlockByHeight(17564306); //ICX dividends var trx = icxBlock.ConfirmedTransactionList[3]; var txResult = IconGateway.GetTransactionResult(trx.TxHash); trx.TxResultDetails = txResult; var msgStr = JsonConvert.SerializeObject(trx); var func = new ICXDepositReceivedFunction.Function(); func.ProcessRecordAsync(null, msgStr).Wait(); }
public PReps(PRepResult prepResult) { BlockHeight = prepResult.BlockHeight; StartRanking = prepResult.StartRanking; TotalDelegated = IconGateway.IntToDecimal(prepResult.TotalDelegated); TotalStake = IconGateway.IntToDecimal(prepResult.TotalStake); Preps = new List <IcxPrep>(); foreach (var prep in prepResult.Preps) { Preps.Add(new IcxPrep() { Address = prep.Address, BlockHeight = prep.BlockHeight, City = prep.City, Country = prep.Country, Delegated = IconGateway.IntToDecimal(prep.Delegated), Grade = prep.Grade, Irep = IconGateway.IntToDecimal(prep.Irep), IrepUpdateBlockHeight = prep.IrepUpdateBlockHeight, LastGenerateBlockHeight = prep.LastGenerateBlockHeight, Name = prep.Name, Details = prep.Details, Penalty = prep.Penalty, Stake = prep.Stake, Status = prep.Status, TotalBlocks = prep.TotalBlocks, ValidatedBlocks = prep.ValidatedBlocks, DetailInfo = GetDetails(prep.Details) }); } foreach (var prep in Preps) { FirebaseGateway.db.Collection("preps").Document(prep.Address).SetAsync(prep, SetOptions.MergeAll).Wait(); } }
public async Task ProcessRecordAsync(ILambdaContext context, string message) { context.Logger.LogLine($"[{DateTime.Now.ToString()}] Processed record {message}"); ConfirmedTransaction tx = JsonConvert.DeserializeObject <ConfirmedTransaction>(message); string address; string contractAddress; decimal amount; //Subscription to AWS Topic ICX_Contract_Method //Looks for specific events that causes Tokens to be transferred foreach (var eventItem in tx.TxResultDetails.EventLogs) { if (eventItem.Indexed[0].StartsWith("Transfer")) { contractAddress = eventItem.ScoreAddress; address = eventItem.Indexed[2]; amount = IconGateway.GetIcxValueFromHex(eventItem.Indexed[3]); ProcessAddress(context, address, contractAddress, amount); } } await Task.CompletedTask; }
private static void ProcessBlock(ICXBlock block, long icxBlockHeight = -1) { BlockProcessedStatus blockStatus = null; ICXBlock icxBlock = block; long blockHeight = 0; try { //Get block height to process if (icxBlockHeight > 0) { blockHeight = icxBlockHeight; } else { blockHeight = block.Height; } //Get block info from Firebase Console.WriteLine($"Starting to Process Block {blockHeight} in thread {System.Threading.Thread.CurrentThread.ManagedThreadId}"); blockStatus = FirebaseGateway.GetBlockProcessed(blockHeight); if (blockStatus == null) { blockStatus = new BlockProcessedStatus() { height = blockHeight, eventsPublished = 0, retryAttempts = 0 }; } else { if (blockStatus.completed == true) { Console.WriteLine($"Block {blockHeight} is already completed, exiting"); return; } blockStatus.retryAttempts++; } //Get the ICX Block if it not provided if (icxBlockHeight > 0) { icxBlock = IconGateway.GetBlockByHeight(icxBlockHeight); } blockStatus.blockTimestamp = Google.Cloud.Firestore.Timestamp.FromDateTimeOffset(icxBlock.GetTimeStamp().AddHours(-8)); // Check ISCORE var rewards = IconGateway.GetAvailableRewards("hxc147caa988765c13eaa6ca43400c27a0372b9436"); if (rewards < oldRewards || oldRewards == -1) { oldRewards = rewards; } else if (rewards > oldRewards) { blockStatus.eventsPublished++; Console.WriteLine($"ISCORE CHANGED, Pushing event update"); publishIScoreChange(); oldRewards = rewards; } var blockTimeStamp = DateTimeOffset.FromUnixTimeMilliseconds(icxBlock.TimeStamp / 1000).AddHours(8); var oldNess = Convert.ToInt32((DateTime.UtcNow.AddHours(8) - icxBlock.GetTimeStamp()).TotalSeconds); //What do we do Console.WriteLine($"block timestamp {icxBlock.GetTimeStamp()}, oldNess {oldNess} seconds, HEIGHT {icxBlock.Height}, transactions {icxBlock.ConfirmedTransactionList.Count}, eventCount {eventCounter}, retries {blockStatus.retryAttempts} in thread {System.Threading.Thread.CurrentThread.ManagedThreadId}"); foreach (var tx in icxBlock.ConfirmedTransactionList) { var txStr = JsonConvert.SerializeObject(tx); if (tx.From != null && tx.From.StartsWith("hx") && tx.To != null && tx.To.StartsWith("hx")) { blockStatus.eventsPublished++; publishTransferMessage(tx); } if (tx.From != null && tx.From.StartsWith("hx") && tx.To != null && tx.To.StartsWith("cx")) { blockStatus.eventsPublished++; var txResult = IconGateway.GetTransactionResult(tx.TxHash); tx.TxResultDetails = txResult; publishContractMethodMessage(tx); } } blockStatus.completed = true; UpdateBlockStatus(blockStatus, icxBlock); Console.WriteLine($"COMPLETED {icxBlock.Height} in thread {System.Threading.Thread.CurrentThread.ManagedThreadId}"); } catch (Exception ex) { Console.WriteLine($"EXCEPTION : Error on block {blockHeight} : {ex.Message} in thread {System.Threading.Thread.CurrentThread.ManagedThreadId}"); blockStatus.completed = false; blockStatus.lastErrorMessage = ex.Message; UpdateBlockStatus(blockStatus, icxBlock); } }
public static void ProcessDeviceAddress(DeviceRegistration device, Address address) { SendResponse sendResponse = null; if (!device.registrationDate.HasValue) { device.registrationDate = DateTime.UtcNow; } if (device.enablePushIScoreChange == true) { try { var totalRewards = IconGateway.GetAvailableRewards(address); if (address.availableRewardsAsDecimal < totalRewards) { decimal awardedICX = totalRewards - address.availableRewardsAsDecimal; if (string.IsNullOrEmpty(address.Name)) { sendResponse = FirebaseGateway.SendPush(device.token, address.address, $"{address.Symbol} Rewards Available", $"Congratulations! your reward of {totalRewards.ToString("0.##")} {address.Symbol} is ready to be claimed"); } else { sendResponse = FirebaseGateway.SendPush(device.token, address.address, $"{address.Symbol} Rewards Available", $"Congratulations! your reward of {totalRewards.ToString("0.##")} {address.Symbol} is ready to be claimed from {address.Name.ToUpper()}"); } //Now update firestore so we dont send the user duplicate messages address.availableRewards = totalRewards.ToString(); address.lastIScorePushSentDate = DateTime.UtcNow; pushNotificationCount++; } else if (address.availableRewardsAsDecimal > totalRewards) { address.availableRewards = totalRewards.ToString(); } } catch (Exception ex) { Console.WriteLine($"[MAIN] EXCEPTION processing IScore check {ex.Message}"); } } if (address.enablePushDeposits == true) { var addressToggles = FirebaseGateway.GetToggleAddresses("awsdeposits"); if (!addressToggles.Any(a => a == address.address)) //Check if address is NOT in the toggles list { try { var balance = IconGateway.GetBalance(address); if (string.IsNullOrEmpty(address.balance)) { //Store current balance without sending a notification address.balance = balance.ToString(); } else if (address.balanceAsDecimal < balance && balance - address.balanceAsDecimal > 0.005M) //Otherwise user gets a message of receiving 0 { decimal depositReceived = balance - address.balanceAsDecimal; if (string.IsNullOrEmpty(address.Name)) { sendResponse = FirebaseGateway.SendPush(device.token, address.address, $"{address.Symbol} Deposit Received", $"You have received a deposit of {depositReceived.ToString("0.##")} {address.Symbol}"); } else { sendResponse = FirebaseGateway.SendPush(device.token, address.address, $"{address.Symbol} Deposit Received", $"{address.Name.ToUpper()} has received a deposit of {depositReceived.ToString("0.##")} {address.Symbol}"); } //Now update firestore so we dont send the user duplicate messages address.balance = balance.ToString(); address.lastDepositPushSentDate = DateTime.UtcNow; pushNotificationCount++; } else if (address.balanceAsDecimal > balance) { address.balance = balance.ToString(); } } catch (Exception ex) { Console.WriteLine($"[MAIN] EXCEPTION processing Deposit check {ex.Message}"); } } else { } } if (!string.IsNullOrEmpty(device.enablePushProductivityDrop) && device.enablePushProductivityDrop != "disabled" && AllPReps != null) { try { lock (AllPReps) { var prodDrop = decimal.Parse(device.enablePushProductivityDrop); var pReps = IconGateway.GetDelegatedPReps(address); if (pReps != null && pReps.Delegations != null && pReps.Delegations.Length > 0) { foreach (var prep in pReps.Delegations) { var findPrep = AllPReps.Preps.SingleOrDefault(p => p.Address == prep.Address); if (findPrep != null && findPrep.Productivity < prodDrop && findPrep.Grade == 0) { if (device.lastProductivityPushSentDate == null || (DateTime.UtcNow - device.lastProductivityPushSentDate).Value.Days > 1) { sendResponse = FirebaseGateway.SendPush(device.token, address.address, "P-Rep Productivity Warning", $"Warning! Your delegated P-Rep {findPrep.Name}'s productivity has dropped to {findPrep.Productivity.ToString("0.##")}%"); //Now update firestore so we dont send the user duplicate messages device.lastProductivityPushSentDate = DateTime.UtcNow; pushNotificationCount++; } } } } } } catch (Exception ex) { Console.WriteLine($"[MAIN] EXCEPTION processing ProductivityDrop check {ex.Message}"); } } if (sendResponse != null && sendResponse.failure > 0) { if (sendResponse.results.Any(a => a.error == "NotRegistered")) { //This token has become stale, need to remove it from firestore FirebaseGateway.DeleteDevice(device); } } }
public decimal GetIcxValue() { return(IconGateway.GetIcxValueFromHex(Value)); }