Skip to content

Commit 86fa7ea

Browse files
Merge pull request #55 from KristiforMilchev/development
Code refactoring
2 parents c185272 + d350976 commit 86fa7ea

File tree

15 files changed

+770
-676
lines changed

15 files changed

+770
-676
lines changed

Data/AuthenicationHandler.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,20 @@ public class AuthenicationHandler : IAuthenicationService
1313
IUtilities Utilities { get; set; }
1414
IContractService ContractService { get; set; }
1515
IHardwareService HardwareService { get; set; }
16+
ICommunication Communication { get; set; }
1617
public AuthenicationHandler()
1718
{
1819
Utilities = ServiceHelper.GetService<IUtilities>();
1920
ContractService = ServiceHelper.GetService<IContractService>();
2021
HardwareService = ServiceHelper.GetService<IHardwareService>();
22+
Communication = ServiceHelper.GetService<ICommunication>();
2123
}
2224

2325

2426
public string GetDefault()
2527
{
2628
//WIP
27-
return MauiProgram.PublicAddress;
29+
return Communication.PublicAddress;
2830
}
2931

3032
public bool SetupNetwork(string networkName, string networkSymbol, string rpcUrl, int chainID, string blockExplorer)
@@ -100,14 +102,14 @@ public bool ImportToken(string contractAddress, string symbol, int delimiter, in
100102

101103
public Account UnlockWallet(string pass)
102104
{
103-
var privateKey = HardwareService.DecryptAesEncoded(MauiProgram.PK, pass);
105+
var privateKey = HardwareService.DecryptAesEncoded(Communication.PK, pass);
104106

105107
if (string.IsNullOrEmpty(privateKey))
106108
return null;
107109

108110
var chainId = 97;
109-
if (MauiProgram.ActiveNetwork != null)
110-
chainId = MauiProgram.ActiveNetwork.Chainid;
111+
if (Communication.ActiveNetwork != null)
112+
chainId = Communication.ActiveNetwork.Chainid;
111113

112114

113115
var wallet = new Account(privateKey, chainId);

Data/ContractService.cs

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,18 @@ internal class ContractService : IContractService
1717
{
1818

1919
IUtilities Utilities { get; set; }
20+
ICommunication Communication { get; set; }
2021
public ContractService()
2122
{
2223
Utilities = ServiceHelper.GetService<IUtilities>();
24+
Communication = ServiceHelper.GetService<ICommunication>();
2325
}
2426

2527
public async Task<decimal> GetAccountBalance(string endpoint)
2628
{
2729
try
2830
{
29-
var publicKey = MauiProgram.PublicAddress;
31+
var publicKey = Communication.PublicAddress;
3032
var web3 = new Nethereum.Web3.Web3(endpoint);
3133
var balance = await web3.Eth.GetBalance.SendRequestAsync(publicKey);
3234
var etherAmount = Web3.Convert.FromWei(balance.Value);
@@ -144,14 +146,14 @@ public async Task<decimal> CheckUserBalanceForContract(string ownerAddress, stri
144146
public async Task<List<Token>> GetNetworkTokens(int networkId)
145147
{
146148
// On startup, it gets thge list of officially supported tokens by running a query against githubs API
147-
if(MauiProgram.ListedTokens == null)
148-
MauiProgram.ListedTokens = await Utilities.GetRequest<List<ListedToken>>($"https://api.github.com/repos/KristiforMilchev/LInksync-Cold-Storage-Wallet/contents/Models/Tokens");
149+
if(Communication.ListedTokens == null)
150+
Communication.ListedTokens = await Utilities.GetRequest<List<ListedToken>>($"https://api.github.com/repos/KristiforMilchev/LInksync-Cold-Storage-Wallet/contents/Models/Tokens");
149151

150152
//Define a local collection of token.
151153
var tokens = new List<Token>();
152154

153155
//Check if the selected network exists
154-
var getNetworkData = MauiProgram.NetworkSettings.FirstOrDefault(x => x.Id == networkId && x.IsProduction == MauiProgram.IsDevelopment);
156+
var getNetworkData = Communication.NetworkSettings.FirstOrDefault(x => x.Id == networkId && x.IsProduction == Communication.IsDevelopment);
155157

156158
//In case it exists we add the native token to the list and run a query to get the user balance of the token.
157159
if(getNetworkData != null)
@@ -176,7 +178,7 @@ public async Task<List<Token>> GetNetworkTokens(int networkId)
176178
}
177179

178180
//Gets the list of officially supported tokens on the selected network, as it binds user balance, market cap, price, and circulating supply for each token.
179-
tokens = await GetListedTokens(MauiProgram.ListedTokens, tokens, getNetworkData);
181+
tokens = await GetListedTokens(Communication.ListedTokens, tokens, getNetworkData);
180182

181183
//Checks if the user has imported tokens in case it the file doesn't exists it creates a blank one.
182184
if (!File.Exists($"{Utilities.GetOsSavePath()}/LocalTokens.json"))
@@ -315,7 +317,7 @@ public async Task<decimal> CheckExistingSupply(string contractAddress, string en
315317

316318
public async Task<decimal> GetImportedData(NetworkSettings network, TokenContract getContract)
317319
{
318-
return await CheckUserBalanceForContract(MauiProgram.PublicAddress, getContract.ContractAddress, network.Endpoint, getContract.Decimals);
320+
return await CheckUserBalanceForContract(Communication.PublicAddress, getContract.ContractAddress, network.Endpoint, getContract.Decimals);
319321
}
320322

321323
public async Task<List<Token>> GetListedTokens(List<ListedToken> listedTokenData, List<Token> tokens, NetworkSettings network)
@@ -337,7 +339,7 @@ public async Task<List<Token>> GetListedTokens(List<ListedToken> listedTokenData
337339
if(getContract != null)
338340
{
339341
//Check the user balance of the given contract
340-
getContract.UserBalance = await CheckUserBalanceForContract(MauiProgram.PublicAddress, getContract.ContractAddress, network.Endpoint, getContract.Decimals);
342+
getContract.UserBalance = await CheckUserBalanceForContract(Communication.PublicAddress, getContract.ContractAddress, network.Endpoint, getContract.Decimals);
341343
//Get the contract native price
342344
var getTokenPrice = await CheckContractPrice(getContract.MainLiquidityPool, getContract.ContractAddress, getContract.PairTokenAddress, getContract.Decimals, 18, network.Endpoint);
343345

@@ -418,7 +420,7 @@ public async Task<bool> ExecutePayments(string receiver, TokenContract token, de
418420
{
419421
Console.WriteLine(e);
420422
logged = true;
421-
MauiProgram.TxHash = "-";
423+
Communication.TxHash = "-";
422424
}
423425

424426
//If transaction hash has been created, start monitoring for a receipt.
@@ -429,7 +431,7 @@ public async Task<bool> ExecutePayments(string receiver, TokenContract token, de
429431
{
430432

431433
txHash = transactionReceipt;
432-
MauiProgram.TxHash = txHash;
434+
Communication.TxHash = txHash;
433435
}
434436
}
435437
return true;
@@ -451,13 +453,13 @@ public async Task<bool> ExecuteNative(string receiver, decimal amountToSend, Net
451453
try
452454
{
453455
var trans = transaction.TransferEtherAsync(receiver, amountToSend, null, null, nounceVal).GetAwaiter().GetResult();
454-
MauiProgram.TxHash = trans;
456+
Communication.TxHash = trans;
455457
return true;
456458

457459
}
458460
catch (Exception e)
459461
{
460-
MauiProgram.TxHash = "-";
462+
Communication.TxHash = "-";
461463
Console.WriteLine(e);
462464
return false;
463465
}

Data/HardwareService.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ namespace NFTLock.Data
2020
internal class HardwareService : IHardwareService
2121
{
2222
IUtilities Utilities = ServiceHelper.GetService<IUtilities>();
23-
23+
ICommunication Communication = ServiceHelper.GetService<ICommunication>();
2424

2525
public string DeviceConnected()
2626
{
@@ -33,7 +33,7 @@ public string DeviceConnected()
3333
foreach (string port in portNames)
3434
{
3535
Debug.WriteLine(port);
36-
MauiProgram.ComPort = port;
36+
Communication.ComPort = port;
3737
current = port;
3838
}
3939

@@ -67,7 +67,7 @@ public bool CreateNewDevice(string port)
6767

6868

6969
//Uploads the firmware to device.
70-
ConfigureHardware(MauiProgram.DeviceType, @$"{Utilities.GetOsSavePath()}\wallet.ino.standard.hex", port);
70+
ConfigureHardware(Communication.DeviceType, @$"{Utilities.GetOsSavePath()}\wallet.ino.standard.hex", port);
7171

7272
Debug.WriteLine("Device Updated");
7373
return true;

Data/PaymentService.cs

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,28 +23,30 @@ internal class PaymentService : IPaymentService
2323
IContractService ContractService { get; set; }
2424
IUtilities Utilities { get; set; }
2525
IAuthenicationService AuthenicationService { get; set; }
26+
ICommunication Communication { get; set; }
2627

2728
//Init the constructor and inherit all dependencies.
2829
public PaymentService()
2930
{
3031
ContractService = ServiceHelper.GetService<IContractService>();
3132
Utilities = ServiceHelper.GetService<IUtilities>();
3233
AuthenicationService = ServiceHelper.GetService<IAuthenicationService>();
34+
Communication = ServiceHelper.GetService<ICommunication>();
3335
}
3436

3537
public async Task<TransactionResult> BeginTransaction()
3638
{
37-
var wallet = AuthenicationService.UnlockWallet(MauiProgram.Pass); //One of decrypt the PK encoded on the device and open the wallet.
39+
var wallet = AuthenicationService.UnlockWallet(Communication.Pass); //One of decrypt the PK encoded on the device and open the wallet.
3840

3941
//If wallet doesn't exist return null
4042
if(wallet == null)
4143
return null;
4244

4345
//Check if a contract exists (Native currencies don't have a contract) if false, send native chain token.
44-
if (string.IsNullOrEmpty(MauiProgram.SelectedContract.ContractAddress))
45-
await ContractService.ExecuteNative(MauiProgram.ReceiverAddress, MauiProgram.Amount, wallet, MauiProgram.ActiveNetwork.Endpoint, MauiProgram.ActiveNetwork.Chainid);
46+
if (string.IsNullOrEmpty(Communication.SelectedContract.ContractAddress))
47+
await ContractService.ExecuteNative(Communication.ReceiverAddress, Communication.Amount, wallet, Communication.ActiveNetwork.Endpoint, Communication.ActiveNetwork.Chainid);
4648
else
47-
await ContractService.ExecutePayments(MauiProgram.ReceiverAddress, MauiProgram.SelectedContract, MauiProgram.Amount, wallet, MauiProgram.ActiveNetwork.Endpoint, MauiProgram.ActiveNetwork.Chainid);
49+
await ContractService.ExecutePayments(Communication.ReceiverAddress, Communication.SelectedContract, Communication.Amount, wallet, Communication.ActiveNetwork.Endpoint, Communication.ActiveNetwork.Chainid);
4850

4951
//Defer next check, it will be validated after the next block regardless.
5052
var dateTime = DateTime.UtcNow.AddSeconds(30);
@@ -55,12 +57,12 @@ public async Task<TransactionResult> BeginTransaction()
5557
//If time is over the check time validate if the transaction is validated
5658
if(DateTime.UtcNow > dateTime)
5759
{
58-
await ValidateTransaction(MauiProgram.TxHash);
60+
await ValidateTransaction(Communication.TxHash);
5961
dateTime = DateTime.UtcNow.AddSeconds(30);
6062
}
6163

6264
}
63-
MauiProgram.ClearCredentials();
65+
Communication.ClearCredentials();
6466
return TransactionResult;
6567
}
6668

@@ -69,7 +71,7 @@ public async Task<bool> ValidateTransaction(string txHash)
6971
{
7072
//We don't need a real wallet here, Pass is empty however due to how Nethereum operates we need to make the request from the object, so we can inherit the chain
7173
//That's why we just instance a object to interact with the chain.
72-
var account = AuthenicationService.UnlockWallet(MauiProgram.Pass);
74+
var account = AuthenicationService.UnlockWallet(Communication.Pass);
7375

7476
//If Hash is empty return false. Return an empty object to avoid recursion in the loop.
7577
if (string.IsNullOrEmpty(txHash))
@@ -78,7 +80,7 @@ public async Task<bool> ValidateTransaction(string txHash)
7880
{
7981
TransactionHash = "-1"
8082
};
81-
MauiProgram.TxHash = string.Empty;
83+
Communication.TxHash = string.Empty;
8284
return false;
8385
}
8486

@@ -93,13 +95,13 @@ public async Task<bool> ValidateTransaction(string txHash)
9395
Timestamp = DateTime.UtcNow,
9496
TransactionHash = "Transaction failed, internal error, insuficient balance or gas!"
9597
};
96-
MauiProgram.TxHash = string.Empty;
98+
Communication.TxHash = string.Empty;
9799
return false;
98100
}
99101

100102
//Create a new web3 instance, using the account object, for the chain data and the current selected network.
101103
//We send a request to the blockchain to check the receipt of the transaction.
102-
var web3 = new Web3(account, MauiProgram.ActiveNetwork.Endpoint);
104+
var web3 = new Web3(account, Communication.ActiveNetwork.Endpoint);
103105
var transactionReceipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txHash);
104106
if (transactionReceipt == null) //Check if transaction is processed in case it fails sent it to quoue;
105107
{
@@ -122,7 +124,7 @@ public async Task<bool> ValidateTransaction(string txHash)
122124
Timestamp = DateTime.UtcNow,
123125
TransactionHash = transactionReceipt.TransactionHash
124126
};
125-
MauiProgram.TxHash = string.Empty;
127+
Communication.TxHash = string.Empty;
126128
return true;
127129
}
128130
else if (transactionReceipt.Failed())
@@ -135,7 +137,7 @@ public async Task<bool> ValidateTransaction(string txHash)
135137
Timestamp = DateTime.UtcNow,
136138
TransactionHash = "Transaction failed, internal error, insuficient balance or gas!"
137139
};
138-
MauiProgram.TxHash = string.Empty;
140+
Communication.TxHash = string.Empty;
139141
return false;
140142
}
141143
}
@@ -144,12 +146,11 @@ public async Task<bool> ValidateTransaction(string txHash)
144146
var transferEvent = transferEventOutput.FirstOrDefault().Event;
145147

146148
//We get the ETH contract actual tokens by substracting the decimals that are obsolete
147-
var actualTransfer = Utilities.ConvertToDex((decimal)transferEvent.Value, MauiProgram.SelectedContract.Decimals);
148-
if (transferEvent.From.ToUpper() != MauiProgram.PublicAddress.ToUpper() || actualTransfer < 0)
149+
var actualTransfer = Utilities.ConvertToDex((decimal)transferEvent.Value, Communication.SelectedContract.Decimals);
150+
if (transferEvent.From.ToUpper() != Communication.PublicAddress.ToUpper() || actualTransfer < 0)
149151
return false;
150152

151-
MauiProgram.TxHash = string.Empty;
152-
153+
153154
TransactionResult = new TransactionResult
154155
{
155156
Amount = actualTransfer,
@@ -158,7 +159,7 @@ public async Task<bool> ValidateTransaction(string txHash)
158159
Timestamp = DateTime.UtcNow,
159160
TransactionHash = transactionReceipt.TransactionHash
160161
};
161-
MauiProgram.TxHash = string.Empty;
162+
Communication.TxHash = string.Empty;
162163

163164
return true;
164165
}

0 commit comments

Comments
 (0)