-
Notifications
You must be signed in to change notification settings - Fork 0
/
TransactionsManager.cs
301 lines (242 loc) · 9.56 KB
/
TransactionsManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
using Nft.App.Models;
using Newtonsoft.Json.Schema.Generation;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Linq;
using Nft.App.Repository;
using Nft.Common;
namespace Nft.App
{
public class TransactionsManager : ITransactionsManager
{
/// <summary>
/// Allowed transaction operations.
/// </summary>
private const string Mint = "Mint";
private const string Burn = "Burn";
private const string Transfer = "Transfer";
private readonly IFileSystem _fileSystemWorker;
private TokenStorage _tokenStorage;
public TransactionsManager(IFileSystem fileSystemWorker)
{
_fileSystemWorker = fileSystemWorker;
_tokenStorage = new TokenStorage();
}
#region Public members
/// <summary>
/// Tries to recover state from previous run.
/// </summary>
public async Task<bool> InitializeAsync()
{
bool result = true;
try
{
_tokenStorage = await _fileSystemWorker.ReadAsync();
}
catch
{
result = false;
}
if (_tokenStorage == null)
_tokenStorage = new TokenStorage();
return result;
}
/// <summary>
/// Reset the state and save the clean state.
/// </summary>
public async Task<bool> ClearAsync()
{
_tokenStorage = new TokenStorage();
return await _fileSystemWorker.SaveAsync(_tokenStorage);
// return await _fileSystemWorker.DeleteAsync(); // I decided not to delete the file, but instead, to rewrite the one.
}
/// <summary>
/// Save on disk.
/// </summary>
public async Task<bool> PersistAsync()
{
return await _fileSystemWorker.SaveAsync(_tokenStorage);
}
/// <summary>
/// Finds list of tokens owned by wallet.
/// </summary>
public async Task<List<string>> GetTokensAsync(string walletId)
{
var result = new List<string>();
if (_tokenStorage.WalletNftTokensMap.ContainsKey(walletId) &&
_tokenStorage.WalletNftTokensMap[walletId] != null)
{
result = _tokenStorage.WalletNftTokensMap[walletId];
result.Sort();
}
return await Task.FromResult(result);
}
/// <summary>
/// Find the wallet which is owning the token.
/// </summary>
public async Task<string> FindWalletOwnerAsync(string tokenId)
{
if (_tokenStorage.NftTokenWalletMap.ContainsKey(tokenId))
{
return await Task<string>.FromResult(_tokenStorage.NftTokenWalletMap[tokenId]);
}
return null;
}
/// <summary>
/// Reads JSON with transactions and executes it.
/// </summary>
/// <exception cref="Newtonsoft.Json.JsonReaderException">I let it fail in case of wrong JSON</exception>
/// <returns>Number of found transactions (but may not all be executed due to validation issues).</returns>
public async Task<int> LoadFromJsonAsync(string json)
{
JToken token = null;
token = JToken.Parse(json);
if (token is JArray)
{
return await RebuildInMemoryStateAsync(JArray.Parse(json));
}
else if (token is JObject)
{
return await RebuildInMemoryStateAsync(JObject.Parse(json));
}
return 0;
}
/// <summary>
/// Reads file with transactions and executes it.
/// </summary>
/// <exception cref="Newtonsoft.Json.JsonReaderException">I let it fail in case of wrong JSON file</exception>
/// <returns>Number of found transactions (but may not all be executed due to validation issues).</returns>
public async Task<int> LoadFromFileAsync(FileInfo file)
{
var data = await File.ReadAllTextAsync(file.FullName);
return await LoadFromJsonAsync(data);
}
#endregion
#region Private members
private async Task<int> RebuildInMemoryStateAsync(JObject transactionJson)
{
if (transactionJson == null)
return 0;
JSchemaGenerator generator = new JSchemaGenerator();
JSchema transactionSchema = generator.Generate(typeof(Transaction));
if (transactionJson.IsValid(transactionSchema))
{
var transaction = transactionJson.ToObject<Transaction>();
if (await ExecuteTransactionAsync(transaction))
{
return 1;
}
}
return 0;
}
private async Task<int> RebuildInMemoryStateAsync(JArray transactionsJson)
{
if (transactionsJson == null)
return 0;
JSchemaGenerator generator = new JSchemaGenerator();
JSchema collectionSchema = generator.Generate(typeof(TransactionsList));
if (transactionsJson.IsValid(collectionSchema))
{
var transactions = transactionsJson.ToObject<TransactionsList>();
foreach (var transaction in transactions)
{
await ExecuteTransactionAsync(transaction);
}
return transactions.Count();
}
return 0;
}
private async Task<bool> ExecuteTransactionAsync(Transaction transaction)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
bool result = true;
switch (transaction.Type)
{
case Mint:
result = AddNFTToken(transaction.TokenId, transaction.Address);
break;
case Burn:
BurnNFTToken(transaction.TokenId);
break;
case Transfer:
result = ChangeOwnership(transaction.TokenId, transaction.From, transaction.To); // Apply change
break;
default:
result = false;
break;
}
return await Task.FromResult(result);
}
// To add an NFT token with owner to the data structure
private bool AddNFTToken(string tokenId, string walletAddress)
{
if (!_tokenStorage.NftTokenWalletMap.ContainsKey(tokenId)) // I assume that tokens must be unique.
{
if (!_tokenStorage.WalletNftTokensMap.ContainsKey(walletAddress))
{
_tokenStorage.WalletNftTokensMap.Add(walletAddress, new List<string>());
}
_tokenStorage.WalletNftTokensMap[walletAddress].Add(tokenId);
_tokenStorage.NftTokenWalletMap.Add(tokenId, walletAddress);
// Create an Ownership entry
var nftToken = new NFTToken
{
TokenId = tokenId,
OwnershipInfo = new LinkedList<OwnershipInfo>()
};
nftToken.OwnershipInfo.AddFirst(
new OwnershipInfo
{
WalletAddress = walletAddress,
Timestamp = DateTime.Now
});
_tokenStorage.NftTokenOwnershipMap.Add(tokenId, nftToken);
return true;
}
return false;
}
private void BurnNFTToken(string tokenId)
{
if (_tokenStorage.NftTokenWalletMap.ContainsKey(tokenId))
{
string walletId = _tokenStorage.NftTokenWalletMap[tokenId];
_tokenStorage.NftTokenWalletMap.Remove(tokenId);
if (_tokenStorage.WalletNftTokensMap.ContainsKey(walletId))
{
_tokenStorage.WalletNftTokensMap.Remove(walletId);
}
}
if (_tokenStorage.NftTokenOwnershipMap.ContainsKey(tokenId))
{
_tokenStorage.NftTokenOwnershipMap.Remove(tokenId);
}
}
private bool ChangeOwnership(string tokenId, string oldWalletAddress, string newWalletAddress)
{
if (_tokenStorage.NftTokenWalletMap.ContainsKey(tokenId) &&
_tokenStorage.NftTokenWalletMap[tokenId].Equals(oldWalletAddress)) // Validate that token is actually owned by From
{
//string oldWalletAddress = _tokenStorage.NftTokenWalletMap[tokenId];
_tokenStorage.WalletNftTokensMap[oldWalletAddress].Remove(tokenId);
if (!_tokenStorage.WalletNftTokensMap.ContainsKey(newWalletAddress))
{
_tokenStorage.WalletNftTokensMap.Add(newWalletAddress, new List<string>());
}
_tokenStorage.WalletNftTokensMap[newWalletAddress].Add(tokenId);
_tokenStorage.NftTokenWalletMap[tokenId] = newWalletAddress;
NFTToken nftToken = _tokenStorage.NftTokenOwnershipMap[tokenId];
nftToken.OwnershipInfo.AddFirst(
new OwnershipInfo
{
WalletAddress = newWalletAddress,
Timestamp = DateTime.Now
});
return true;
}
return false;
}
#endregion
}
}