Skip to content

Commit c185272

Browse files
Merge pull request #54 from KristiforMilchev/development
Code refactoring, adding comments to methods.
2 parents a0fcd56 + 8043d85 commit c185272

File tree

12 files changed

+594
-256
lines changed

12 files changed

+594
-256
lines changed

Data/AuthenicationHandler.cs

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,7 @@ public AuthenicationHandler()
2020
HardwareService = ServiceHelper.GetService<IHardwareService>();
2121
}
2222

23-
public string CreateAccountInitial()
24-
{
25-
//WIP
26-
return string.Empty;
27-
}
28-
29-
public async Task<string> DeployContract()
30-
{
31-
//WIP
32-
return string.Empty;
33-
}
34-
23+
3524
public string GetDefault()
3625
{
3726
//WIP
@@ -132,16 +121,6 @@ public async Task<List<Token>> GetSupportedTokens(int networkId)
132121
return await ContractService.GetNetworkTokens(networkId);
133122

134123
}
135-
136-
string IAuthenicationService.ToHex(byte[] value, bool prefix)
137-
{
138-
return System.Text.Encoding.UTF8.GetString(value);
139-
}
140-
141-
byte IAuthenicationService.ConvertBinaryToText(string seq)
142-
{
143-
return Convert.ToByte(seq, 2);
144-
}
145124
}
146125

147126

Data/ContractService.cs

Lines changed: 196 additions & 137 deletions
Large diffs are not rendered by default.

Data/HardwareService.cs

Lines changed: 19 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -24,19 +24,19 @@ internal class HardwareService : IHardwareService
2424

2525
public string DeviceConnected()
2626
{
27+
//Get an array of com ports on the system
2728
string[] portNames = SerialPortStream.GetPortNames();
2829

29-
// string[] ports = SerialPort.GetPortNames();
30-
31-
Debug.WriteLine("The following serial ports were found:");
3230
var current = string.Empty;
3331
// Display each port name to the console.
32+
//Always assigns the last com port to the system, doesn't work with two devices.
3433
foreach (string port in portNames)
3534
{
3635
Debug.WriteLine(port);
3736
MauiProgram.ComPort = port;
3837
current = port;
3938
}
39+
4040
return current;
4141
}
4242

@@ -49,27 +49,28 @@ public bool CreateNewDevice(string port)
4949
{
5050
string userName = Environment.UserName;
5151

52-
53-
if (!File.Exists(@$"{Utilities.GetOsSavePath()}\wallet.ino.standard.hex"))
52+
//If file exists, delete it, we want the latest version of the file.
53+
if (File.Exists(@$"{Utilities.GetOsSavePath()}\wallet.ino.standard.hex"))
54+
File.Delete(@$"{Utilities.GetOsSavePath()}\wallet.ino.standard.hex");
55+
56+
57+
//Download the latest version of the file.
58+
using (WebClient wc = new WebClient())
5459
{
55-
using (WebClient wc = new WebClient())
56-
{
5760

58-
wc.DownloadFile(
59-
// Param1 = Link of file
60-
new System.Uri("https://raw.githubusercontent.com/KristiforMilchev/LInksync-Cold-Storage-Wallet/main/HardwareCode/ColdStorage/wallet.ino.standard.hex"),
61-
// Param2 = Path to save
62-
@$"{Utilities.GetOsSavePath()}\wallet.ino.standard.hex"
63-
);
64-
}
61+
wc.DownloadFile(
62+
// Param1 = Link of file
63+
new System.Uri("https://raw.githubusercontent.com/KristiforMilchev/LInksync-Cold-Storage-Wallet/main/HardwareCode/ColdStorage/wallet.ino.standard.hex"),
64+
// Param2 = Path to save
65+
@$"{Utilities.GetOsSavePath()}\wallet.ino.standard.hex");
6566
}
6667

6768

69+
//Uploads the firmware to device.
6870
ConfigureHardware(MauiProgram.DeviceType, @$"{Utilities.GetOsSavePath()}\wallet.ino.standard.hex", port);
6971

7072
Debug.WriteLine("Device Updated");
7173
return true;
72-
7374
}
7475

7576
public void ConfigureHardware(ArduinoModel device,string path, string port)
@@ -92,6 +93,7 @@ public CryptoWallet ImportAccount(List<Word> words)
9293
var Pk = string.Empty;
9394
var i = 0;
9495

96+
//Loop over the words and reconstruct the key
9597
words.ForEach(x =>
9698
{
9799
Pk += x.Name;
@@ -136,36 +138,17 @@ public List<Word> GenerateWords(List<string> chunks)
136138
List<Word> words = new List<Word>();
137139
chunks.ToList().ForEach(x =>
138140
{
139-
string yourByteString = x;
140-
141-
142-
143141
words.Add(new Word
144142
{
145-
Name = yourByteString,
143+
Name = x,
146144
Index = i,
147145
});
148146
i++;
149147

150148
});
151149
return words;
152150
}
153-
154-
public string GeneratePrivateKey(List<string> data)
155-
{
156-
byte[] bytes = new byte[data.Count+1];
157-
var i = 0;
158-
data.ForEach(x =>
159-
{
160-
var cByte = Convert.ToByte(x, 2);
161-
bytes[i] = cByte;
162-
i++;
163-
});
164-
165-
var pk = bytes.ToHex();
166-
return pk;
167-
}
168-
151+
169152
public string Encrypt(string data, string password)
170153
{
171154
try

Data/PaymentService.cs

Lines changed: 40 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ internal class PaymentService : IPaymentService
2323
IContractService ContractService { get; set; }
2424
IUtilities Utilities { get; set; }
2525
IAuthenicationService AuthenicationService { get; set; }
26+
27+
//Init the constructor and inherit all dependencies.
2628
public PaymentService()
2729
{
2830
ContractService = ServiceHelper.GetService<IContractService>();
@@ -32,30 +34,25 @@ public PaymentService()
3234

3335
public async Task<TransactionResult> BeginTransaction()
3436
{
35-
36-
MauiProgram.HideTokenList = "none";
37-
MauiProgram.HideTokenSend = "none";
38-
MauiProgram.ShowPinPanel = "none";
39-
40-
41-
var wallet = AuthenicationService.UnlockWallet(MauiProgram.Pass);
37+
var wallet = AuthenicationService.UnlockWallet(MauiProgram.Pass); //One of decrypt the PK encoded on the device and open the wallet.
4238

39+
//If wallet doesn't exist return null
4340
if(wallet == null)
4441
return null;
4542

43+
//Check if a contract exists (Native currencies don't have a contract) if false, send native chain token.
4644
if (string.IsNullOrEmpty(MauiProgram.SelectedContract.ContractAddress))
4745
await ContractService.ExecuteNative(MauiProgram.ReceiverAddress, MauiProgram.Amount, wallet, MauiProgram.ActiveNetwork.Endpoint, MauiProgram.ActiveNetwork.Chainid);
4846
else
4947
await ContractService.ExecutePayments(MauiProgram.ReceiverAddress, MauiProgram.SelectedContract, MauiProgram.Amount, wallet, MauiProgram.ActiveNetwork.Endpoint, MauiProgram.ActiveNetwork.Chainid);
5048

51-
//Clear PK, password etc.
52-
53-
54-
55-
var dateTime = DateTime.UtcNow.AddSeconds(30);
49+
//Defer next check, it will be validated after the next block regardless.
50+
var dateTime = DateTime.UtcNow.AddSeconds(30);
5651

52+
//Loop and wait till the transaction was valid, important no recursion here due to that the transaction hash has already been created we are only checking the status.
5753
while(TransactionResult == null)
5854
{
55+
//If time is over the check time validate if the transaction is validated
5956
if(DateTime.UtcNow > dateTime)
6057
{
6158
await ValidateTransaction(MauiProgram.TxHash);
@@ -70,12 +67,22 @@ public async Task<TransactionResult> BeginTransaction()
7067

7168
public async Task<bool> ValidateTransaction(string txHash)
7269
{
73-
70+
//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
71+
//That's why we just instance a object to interact with the chain.
7472
var account = AuthenicationService.UnlockWallet(MauiProgram.Pass);
7573

74+
//If Hash is empty return false. Return an empty object to avoid recursion in the loop.
7675
if (string.IsNullOrEmpty(txHash))
76+
{
77+
TransactionResult = new TransactionResult
78+
{
79+
TransactionHash = "-1"
80+
};
81+
MauiProgram.TxHash = string.Empty;
7782
return false;
78-
83+
}
84+
85+
//If the transaction failed at creation, and there is no hash we return an error object.
7986
if(txHash == "-")
8087
{
8188
TransactionResult = new TransactionResult
@@ -84,12 +91,14 @@ public async Task<bool> ValidateTransaction(string txHash)
8491
From = "--",
8592
To = "--",
8693
Timestamp = DateTime.UtcNow,
87-
TransactionHash = "Transaction failed, internal error, inssuficient balance or gas!"
94+
TransactionHash = "Transaction failed, internal error, insuficient balance or gas!"
8895
};
89-
MauiProgram.TxHash = String.Empty;
96+
MauiProgram.TxHash = string.Empty;
9097
return false;
9198
}
9299

100+
//Create a new web3 instance, using the account object, for the chain data and the current selected network.
101+
//We send a request to the blockchain to check the receipt of the transaction.
93102
var web3 = new Web3(account, MauiProgram.ActiveNetwork.Endpoint);
94103
var transactionReceipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txHash);
95104
if (transactionReceipt == null) //Check if transaction is processed in case it fails sent it to quoue;
@@ -98,6 +107,8 @@ public async Task<bool> ValidateTransaction(string txHash)
98107
return false;
99108
}
100109

110+
//Decode events in case it's a proxy contract, ETC ETH smart contract
111+
//If transferEventOutput is 0, it's a native token transfer.
101112
var transferEventOutput = transactionReceipt.DecodeAllEvents<TransferEventDTO>();
102113
if (transferEventOutput.Count == 0)
103114
{
@@ -111,21 +122,28 @@ public async Task<bool> ValidateTransaction(string txHash)
111122
Timestamp = DateTime.UtcNow,
112123
TransactionHash = transactionReceipt.TransactionHash
113124
};
114-
MauiProgram.TxHash = String.Empty;
125+
MauiProgram.TxHash = string.Empty;
115126
return true;
116127
}
117128
else if (transactionReceipt.Failed())
118129
{
119-
120-
MauiProgram.TxHash = String.Empty;
130+
TransactionResult = new TransactionResult
131+
{
132+
Amount = 0,
133+
From = "--",
134+
To = "--",
135+
Timestamp = DateTime.UtcNow,
136+
TransactionHash = "Transaction failed, internal error, insuficient balance or gas!"
137+
};
138+
MauiProgram.TxHash = string.Empty;
121139
return false;
122140
}
123141
}
124142

125-
143+
//Get the initial main trainsfer event.
126144
var transferEvent = transferEventOutput.FirstOrDefault().Event;
127145

128-
146+
//We get the ETH contract actual tokens by substracting the decimals that are obsolete
129147
var actualTransfer = Utilities.ConvertToDex((decimal)transferEvent.Value, MauiProgram.SelectedContract.Decimals);
130148
if (transferEvent.From.ToUpper() != MauiProgram.PublicAddress.ToUpper() || actualTransfer < 0)
131149
return false;
@@ -140,7 +158,7 @@ public async Task<bool> ValidateTransaction(string txHash)
140158
Timestamp = DateTime.UtcNow,
141159
TransactionHash = transactionReceipt.TransactionHash
142160
};
143-
MauiProgram.TxHash = String.Empty;
161+
MauiProgram.TxHash = string.Empty;
144162

145163
return true;
146164
}

Models/TransactionResult.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ namespace SYNCWallet.Models
88
{
99
public class TransactionResult
1010
{
11-
public string TransactionHash { get; set;
12-
}
11+
public string TransactionHash { get; set;}
1312
public string From { get; set; }
1413
public string To { get; set; }
1514
public decimal Amount { get; set; }

Services/Definitions/IAuthenicationService.cs

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,40 @@ namespace SYNCWallet.Services.Definitions
1010
{
1111
public interface IAuthenicationService
1212
{
13-
public string CreateAccountInitial();
14-
public Task<string> DeployContract();
13+
/// <summary>
14+
/// Gets the public key of the connected wallet.
15+
/// </summary>
1516
public string GetDefault();
17+
/// <summary>
18+
/// Impoirts a custom EVM compatible blockchain network
19+
/// Parameters:
20+
/// <param name="networkName">Name of the network</param>
21+
/// <param name="networkSymbol">SYMBOL of the network</param>
22+
/// <param name="rpcUrl">rpc endpoint of the network</param>
23+
/// <param name="chainID">chain idof the network</param>
24+
/// <param name="blockExplorer">https block explorer</param>
25+
/// </summary>
1626
public bool SetupNetwork(string networkName, string networkSymbol, string rpcUrl, int chainID, string blockExplorer);
27+
/// <summary>
28+
/// Imports custom token not listed on the official list.
29+
/// Parameters:
30+
/// <param name="contractAddress">Address of the contract that we import </param>
31+
/// <param name="symbol">Token Symbol</param>
32+
/// <param name="delimiter">Decimal count of the token</param>
33+
/// <param name="network">Internal network id of the network under which we import the token</param>
34+
/// </summary>
1735
public bool ImportToken(string contractAddress, string symbol, int delimiter, int network);
36+
/// <summary>
37+
/// Attepmts to decrypt and unlock a web3 wallet using a password
38+
/// Parameters:
39+
/// <param name="pass">Password used to encrypt the wallet.</param>
40+
/// </summary>
1841
public Account UnlockWallet(string pass);
42+
/// <summary>
43+
/// Gets a list of supported tokens filtered by network id
44+
/// Parameters:
45+
/// <param name="networkId">Blockchain endpoint, RPC address of the Blockchain network </param>
46+
/// </summary>
1947
public Task<List<Token>> GetSupportedTokens(int networkId);
20-
string ToHex(byte[] value, bool prefix = false);
21-
byte ConvertBinaryToText(string seq);
22-
23-
24-
2548
}
2649
}

0 commit comments

Comments
 (0)