-
Notifications
You must be signed in to change notification settings - Fork 7
/
NeblioTransactionHelpers.cs
2158 lines (1827 loc) · 91.4 KB
/
NeblioTransactionHelpers.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using NBitcoin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using VEDriversLite.Events;
using VEDriversLite.Dto;
using VEDriversLite.Neblio;
using VEDriversLite.NeblioAPI;
using VEDriversLite.Security;
using VEDriversLite.Common;
using static Google.Protobuf.WellKnownTypes.Field;
using static System.Net.WebRequestMethods;
namespace VEDriversLite
{
/// <summary>
/// Main Helper class for the Neblio Blockchain Transactions
/// </summary>
public static class NeblioTransactionHelpers
{
/// <summary>
/// NBitcoin Instance of Mainet Network of Neblio
/// </summary>
public static Network Network = NBitcoin.Altcoins.Neblio.Instance.Mainnet;
/// <summary>
/// Conversion ration for Neblio to convert from sat to 1 NEBL
/// </summary>
public const double FromSatToMainRatio = 100000000;
/// <summary>
/// Minimum amount in Satoshi on Neblio Blockchain
/// </summary>
public static long MinimumAmount = 10000;
/// <summary>
/// Main event info handler
/// </summary>
public static event EventHandler<IEventInfo> NewEventInfo;
/// <summary>
/// This function will calculate the fee based of the known lenght of the intputs and the outputs
/// If there is the OP_RETURN output it is considered as the customMessage. Please fill it for token transactions.
/// Token transaction also will add just for sure one output to calculation of the size for the case there will be some tokens back to original address
/// </summary>
/// <param name="numOfInputs">Number of input of the transaction "in" vector</param>
/// <param name="numOfOutputs">Number of outpus of the transaction "out" vector</param>
/// <param name="customMessageInOPReturn">Custom message - "OP_RETURN" output</param>
/// <param name="isTokenTransaction">Token transaction will add another output for getting back the tokens</param>
/// <returns></returns>
public static double CalcFee(int numOfInputs, int numOfOutputs, string customMessageInOPReturn, bool isTokenTransaction)
{
if (numOfInputs <= 0)
numOfInputs = 1;
if (numOfOutputs <= 0)
numOfOutputs = 1;
const string exceptionMessage = "Cannot send transaction bigger than 4kB on Neblio network!";
var basicFee = MinimumAmount;
// inputs
var blankInput = 41;
var inputSignature = 56;
var signedInput = blankInput + inputSignature;
// outputs
var outputWithAddress = 34;
var emptyOpReturn = 11; // OP_RETURN with custom message with 10 characters had 21 bytes...etc.
//common properties in each transaction
var commonPropertiesSize = 214;
var expectedSize = signedInput * numOfInputs + outputWithAddress * numOfOutputs + commonPropertiesSize;
// add custom message if there is some
if (!string.IsNullOrEmpty(customMessageInOPReturn))
{
var zipstr = StringExt.ZipStr(customMessageInOPReturn);
expectedSize += emptyOpReturn + zipstr.Length;
}
// Expected outputs for the rest of the coins/tokens
expectedSize += outputWithAddress; // NEBL
if (isTokenTransaction)
{
expectedSize += outputWithAddress;
}
double size_m = ((double)expectedSize / 1024);
if (size_m > 3.9)
{
throw new Exception(exceptionMessage);
}
size_m = Math.Ceiling(size_m);
var fee = basicFee + (int)(size_m) * basicFee;
if (isTokenTransaction)
{
fee += basicFee;
}
return fee;
}
private static (BitcoinAddress, BitcoinSecret) GetAddressAndKeyInternal(EncryptionKey ekey, string password)
{
var key = string.Empty;
const string message = "Cannot send token transaction. Password is not filled and key is encrypted or unlock account!";
const string exceptionMessage = "Cannot send token transaction. cannot create keys!";
if (ekey != null)
{
if (ekey.IsLoaded)
{
if (ekey.IsEncrypted && string.IsNullOrEmpty(password) && !ekey.IsPassLoaded)
{
throw new Exception(message);
}
else if (!ekey.IsEncrypted)
{
key = ekey.GetEncryptedKey();
}
else if (ekey.IsEncrypted && (!string.IsNullOrEmpty(password) || ekey.IsPassLoaded))
{
if (ekey.IsPassLoaded)
{
key = ekey.GetEncryptedKey(string.Empty);
}
else
{
key = ekey.GetEncryptedKey(password);
}
}
if (string.IsNullOrEmpty(key))
{
throw new Exception(message);
}
}
}
if (!string.IsNullOrEmpty(key))
{
try
{
BitcoinSecret loadedkey = Network.CreateBitcoinSecret(key);
BitcoinAddress addressForTx = loadedkey.GetAddress(ScriptPubKeyType.Legacy);
return (addressForTx, loadedkey);
}
catch (Exception ex)
{
Console.WriteLine("Cannot send token transaction!", ex);
throw new Exception(exceptionMessage);
}
}
else
{
throw new Exception(message);
}
}
/// <summary>
/// Function converts EncryptionKey (optionaly with password if it is not already loaded in ekey)
/// and returns BitcoinAddress and BitcoinSecret classes from NBitcoin
/// </summary>
/// <param name="ekey"></param>
/// <param name="password"></param>
/// <returns></returns>
public static (BitcoinAddress, BitcoinSecret) GetAddressAndKey(EncryptionKey ekey, string password)
{
return GetAddressAndKeyInternal(ekey, password);
}
/// <summary>
/// Function converts EncryptionKey (optionaly with password if it is not already loaded in ekey)
/// and returns BitcoinAddress and BitcoinSecret classes from NBitcoin
/// </summary>
/// <param name="ekey"></param>
/// <returns></returns>
public static (BitcoinAddress, BitcoinSecret) GetAddressAndKey(EncryptionKey ekey)
{
return GetAddressAndKeyInternal(ekey, "");
}
/// <summary>
/// This function will crate empty Transaction object based on Neblio network standard
/// Then add the Neblio Inputs and sumarize their value
/// </summary>
/// <param name="nutxos">List of Neblio Utxos to use</param>
/// <param name="address">Address of the owner</param>
/// <returns>(NBitcoin Transaction object, sum of all inputs values in double)</returns>
public static (Transaction, double) GetTransactionWithNeblioInputs(ICollection<Utxos> nutxos, BitcoinAddress address)
{
// create template for new tx from last one
var transaction = Transaction.Create(Network);
var allNeblInputCoins = 0.0; //this is because of the optimization. When we iterate through values we can sum them for later use
try
{
// add inputs of tx
foreach (var utxo in nutxos)
{
transaction.Inputs.Add(new TxIn()
{
PrevOut = new OutPoint(uint256.Parse(utxo.Txid), (int)utxo.Index),
ScriptSig = address.ScriptPubKey,
});
allNeblInputCoins += (double)utxo.Value / FromSatToMainRatio;
}
return (transaction, allNeblInputCoins);
}
catch (Exception ex)
{
Console.WriteLine("Exception during loading inputs. " + ex.Message);
}
return (null, 0);
}
/// <summary>
/// This function will create empty Transaction object based on Neblio network standard
/// Then it add Neblio intpus and tokens inputs and summarize their value
/// </summary>
/// <param name="nutxos"></param>
/// <param name="tutxos"></param>
/// <param name="address"></param>
/// <returns>(Item1 - NBitcoin Transaction object, (Item2.Item1 - sum of all neblio inputs, Item2.Item2 - sum of all tokens)</returns>
public static (Transaction, (double, double)) GetTransactionWithNeblioAndTokensInputs(ICollection<Utxos> nutxos, ICollection<Utxos> tutxos, BitcoinAddress address)
{
var txres = GetTransactionWithNeblioInputs(nutxos, address);
var transaction = txres.Item1;
var allNeblInputCoins = txres.Item2; //this is because of the optimization. When we iterate through values we can sum them for later use
var allTokensInputs = 0.0; //this is because of the optimization. When we iterate through values we can sum them for later use
TxInList inputs = new TxInList();
try
{
// add inputs of tx
foreach (var utxo in tutxos)
{
inputs.Add(new TxIn()
{
PrevOut = new OutPoint(uint256.Parse(utxo.Txid), (int)utxo.Index),
ScriptSig = address.ScriptPubKey,
});
allNeblInputCoins += (double)utxo.Value / FromSatToMainRatio;
var toks = utxo.Tokens.FirstOrDefault();
if (toks != null && toks.Amount > 0)
allTokensInputs += toks.Amount ?? 0;
}
foreach (var inp in transaction.Inputs)
inputs.Add(inp);
transaction.Inputs.Clear();
transaction.Inputs.AddRange(inputs);
return (transaction, (allNeblInputCoins, allTokensInputs));
}
catch (Exception ex)
{
Console.WriteLine("Exception during loading inputs. " + ex.Message);
}
return (null, (0.0, 0.0));
}
public static byte[] GetMetaComprimed(IDictionary<string, string> metadata)
{
if (metadata == null)
metadata = new Dictionary<string, string>();
var dto = new SendTokenRequest()
{
Metadata = new Metadata2() { UserData = new UserData3() { Meta = new List<JObject>() } }
};
foreach (var d in metadata)
dto.Metadata.UserData.Meta.Add(new JObject { [d.Key] = d.Value });
var metastring = JsonConvert.SerializeObject(dto.Metadata);
var metacomprimed = StringExt.Compress(Encoding.UTF8.GetBytes(metastring));
return metacomprimed;
}
/// <summary>
/// Issue new tokens. Please check the IssueTokenTxData Dto for input parameters
/// </summary>
/// <param name="data"></param>
/// <param name="nutxos"></param>
/// <param name="fee"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static async Task<Transaction> IssueTokensAsync(IssueTokenTxData data, ICollection<Utxos> nutxos, double fee = 20000)
{
if (data.IssuanceMetadata == null)
throw new Exception("Cannot send without metadata!");
// load key and address
BitcoinAddress addressForTx;
// create receiver address
BitcoinAddress recaddr;
try
{
addressForTx = recaddr = BitcoinAddress.Create(data.SenderAddress, Network);
recaddr = BitcoinAddress.Create(data.ReceiverAddress, Network);
}
catch (Exception)
{
throw new Exception("Cannot send transaction. cannot create receiver address!");
}
var nutxo = nutxos.FirstOrDefault();
if (nutxo == null)
throw new Exception("Cannot send transaction, cannot load sender nebl utxo!");
var txres = GetTransactionWithNeblioInputs(nutxos, addressForTx);
var transaction = txres.Item1;
var allNeblInputCoins = txres.Item2;
var metastring = JsonConvert.SerializeObject(data.IssuanceMetadata);
var metacomprimed = StringExt.Compress(Encoding.UTF8.GetBytes(metastring));
var index = 0;
List<NTP1Instructions> TiList = new List<NTP1Instructions>();
//Now make the transfer instruction
NTP1Instructions ti = new NTP1Instructions();
ti.amount = data.Amount;
ti.vout_num = 0;
TiList.Add(ti);
//Create the hex op_return
string ti_script = NTP1ScriptHelpers._NTP1CreateIsseueScript(TiList, metacomprimed, data.IssuanceMetadata.Data.TokenName, data.Flags);
try
{
fee = CalcFee(transaction.Inputs.Count, 2, metastring, true);
var balanceinSat = Convert.ToUInt64(allNeblInputCoins * FromSatToMainRatio);
var costOfIssuing = Convert.ToUInt64(10 * FromSatToMainRatio); // it cost 10 NEBL to issue new tokens
if ((costOfIssuing + fee) > balanceinSat)
throw new Exception("Not enought spendable Neblio on the address.");
var diffinSat = balanceinSat - costOfIssuing - Convert.ToUInt64(fee) - Convert.ToUInt64(MinimumAmount) - Convert.ToUInt64(MinimumAmount); // fee is already included in previous output, last is token carriers
if (!string.IsNullOrEmpty(data.ReceiverAddress))
transaction.Outputs.Add(new Money(MinimumAmount), recaddr.ScriptPubKey); // send to receiver required amount
else
transaction.Outputs.Add(new Money(MinimumAmount), addressForTx.ScriptPubKey); // send to receiver required amount
var ti_b = NTP1ScriptHelpers.UnhexToByteArray(ti_script);
transaction.Outputs.Add(new TxOut()
{
Value = new Money(MinimumAmount),
ScriptPubKey = CreateOPRETURNScript(ti_b)
});
if (diffinSat > 0)
transaction.Outputs.Add(new Money(diffinSat), addressForTx.ScriptPubKey); // get diff back to sender addresss
}
catch (Exception ex)
{
throw new Exception("Exception during adding outputs with payment in neblio." + ex.Message);
}
return transaction;
}
/// <summary>
/// Send lot of the tokens. It means more than 1 token in one output. Please check the SendTokenTxData Dto for input parameters
/// </summary>
/// <param name="data"></param>
/// <param name="nutxos"></param>
/// <param name="tutxos"></param>
/// <param name="fee"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static Transaction SendTokenLotNewAsync(SendTokenTxData data, ICollection<Utxos> nutxos, ICollection<Utxos> tutxos, double fee = 20000)
{
if (data.Metadata == null || data.Metadata.Count == 0)
throw new Exception("Cannot send without metadata!");
// load key and address
BitcoinSecret key;
BitcoinAddress addressForTx;
// create receiver address
BitcoinAddress recaddr;
try
{
addressForTx = BitcoinAddress.Create(data.SenderAddress, Network);
recaddr = BitcoinAddress.Create(data.ReceiverAddress, Network);
}
catch (Exception)
{
throw new Exception("Cannot send transaction. cannot create receiver address!");
}
var tutxo = tutxos.FirstOrDefault();
if (tutxo == null)
throw new Exception("Cannot send transaction, cannot load sender nebl utxo!");
var nutxo = nutxos.FirstOrDefault();
if (nutxo == null)
throw new Exception("Cannot send transaction, cannot load sender nebl utxo!");
var txres = GetTransactionWithNeblioAndTokensInputs(nutxos, tutxos, addressForTx);
var transaction = txres.Item1;
var allNeblInputCoins = txres.Item2.Item1;
var index = 0;
List<NTP1Instructions> TiList = new List<NTP1Instructions>();
//Now make the transfer instruction
NTP1Instructions ti = new NTP1Instructions();
ti.amount = Convert.ToUInt64(data.Amount);
ti.vout_num = 0;
TiList.Add(ti);
var metacomprimed = GetMetaComprimed(data.Metadata);
//Create the hex op_return
string ti_script = NTP1ScriptHelpers._NTP1CreateTransferScript(TiList, metacomprimed); //No metadata
var restOfToks = txres.Item2.Item2; //txres.Item2.Item2 holds all tokens in inputs tutxos
restOfToks -= data.Amount;
try
{
fee = CalcFee(transaction.Inputs.Count, 2, JsonConvert.SerializeObject(data.Metadata), true);
var balanceinSat = Convert.ToUInt64(allNeblInputCoins * FromSatToMainRatio);
if ((4 * MinimumAmount + fee) > balanceinSat)
throw new Exception("Not enought spendable Neblio on the address.");
var diffinSat = balanceinSat - Convert.ToUInt64(fee) - Convert.ToUInt64(MinimumAmount) - Convert.ToUInt64(MinimumAmount); // fee is already included in previous output, last is token carriers
if (restOfToks > 0)
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), recaddr.ScriptPubKey); // send to receiver required amount
var ti_b = NTP1ScriptHelpers.UnhexToByteArray(ti_script);
transaction.Outputs.Add(new TxOut()
{
Value = new Money(MinimumAmount),
ScriptPubKey = CreateOPRETURNScript(ti_b)
});
if (diffinSat > 0)
transaction.Outputs.Add(new Money(diffinSat), addressForTx.ScriptPubKey); // get diff back to sender address
if (restOfToks > 0) // just for minting new payment nft
transaction.Outputs.Add(new Money(MinimumAmount), addressForTx.ScriptPubKey); // add 10000 sat as carier of tokens which goes back
}
catch (Exception ex)
{
throw new Exception("Exception during adding outputs with payment in neblio." + ex.Message);
}
return transaction;
}
/// <summary>
/// Create OP_RETURN output ScriptPubKey from the input data.
/// Data should not contain OP_RETURN byte. This byte is added in the function. PLease provide just the data which should be attached
/// Data must be in not HEX form. The Op.GetPushOp function converts them during the loading.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static Script CreateOPRETURNScript(params byte[][] data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
Op[] ops = new Op[data.Length + 1];
ops[0] = OpcodeType.OP_RETURN;
for (int i = 0; i < data.Length; i++)
ops[1 + i] = Op.GetPushOp(data[i]);
var script = new Script(ops);
return script;
}
/// <summary>
/// Function will Mint NFT from lot of the tokens
/// </summary>
/// <param name="data">Mint data, please see MintNFTData class for the details</param>
/// <param name="ekey">Input EncryptionKey of the account</param>
/// <param name="nutxos">Optional input neblio utxo</param>
/// <param name="tutxos">Optional input token utxo</param>
/// <returns>New Transaction Hash - TxId</returns>
public static async Task<Transaction> MintNFTTokenAsync(MintNFTData data, ICollection<Utxos> nutxos, ICollection<Utxos> tutxos)
{
return await MintMultiNFTTokenAsyncInternal(data, 0, nutxos, tutxos, false);
}
/// <summary>
/// Function will Mint NFT with the coppies
/// </summary>
/// <param name="data">Mint data, please see MintNFTData class for the details</param>
/// <param name="coppies">0 or more coppies - with 0 input it is same as MintNFTTokenAsync</param>
/// <param name="ekey">Input EncryptionKey of the account</param>
/// <param name="nutxos">Optional input neblio utxo</param>
/// <param name="tutxos">Optional input token utxo</param>
/// <returns>New Transaction Hash - TxId</returns>
public static async Task<Transaction> MintMultiNFTTokenAsync(MintNFTData data, int coppies, ICollection<Utxos> nutxos, ICollection<Utxos> tutxos)
{
return await MintMultiNFTTokenAsyncInternal(data, coppies, nutxos, tutxos, true);
}
/// <summary>
/// Function will Mint NFT with the coppies
/// </summary>
/// <param name="data">Mint data, please see MintNFTData class for the details</param>
/// <param name="coppies">0 or more coppies - with 0 input it is same as MintNFTTokenAsync</param>
/// <param name="ekey">Input EncryptionKey of the account</param>
/// <param name="nutxos">Optional input neblio utxo</param>
/// <param name="tutxos">Optional input token utxo</param>
/// <param name="multiTokens">If there is the multi token it needs to check if there is no conflict</param>
/// <returns>New Transaction Hash - TxId</returns>
public static async Task<Transaction> MintMultiNFTTokenAsyncInternal(MintNFTData data, int coppies, ICollection<Utxos> nutxos, ICollection<Utxos> tutxos, bool multiTokens, double fee = 20000)
{
if (data.Metadata == null || data.Metadata.Count == 0)
throw new Exception("Cannot send without metadata!");
List<BitcoinAddress> receiverAddreses = new List<BitcoinAddress>();
// load key and address
BitcoinSecret key;
BitcoinAddress addressForTx = BitcoinAddress.Create(data.SenderAddress, Network);
if (!string.IsNullOrEmpty(data.ReceiverAddress) || data.MultipleReceivers.Count > 0)
{
if (data.MultipleReceivers.Count == 0)
receiverAddreses.Add(BitcoinAddress.Create(data.ReceiverAddress, Network));
else
{
foreach (var a in data.MultipleReceivers)
receiverAddreses.Add(BitcoinAddress.Create(a, Network));
}
}
var tutxo = tutxos.FirstOrDefault();
if (tutxo == null)
throw new Exception("Cannot send transaction, cannot load sender nebl utxo!");
var nutxo = nutxos.FirstOrDefault();
if (nutxo == null)
throw new Exception("Cannot send transaction, cannot load sender nebl utxo!");
var txres = GetTransactionWithNeblioAndTokensInputs(nutxos, tutxos, addressForTx);
var transaction = txres.Item1;
var allNeblInputCoins = txres.Item2.Item1;
data.Metadata.Add(new KeyValuePair<string, string>("SourceUtxo", tutxo.Txid));
data.Metadata.Add(new KeyValuePair<string, string>("NFT FirstTx", "true"));
List<NTP1Instructions> TiList = new List<NTP1Instructions>();
//Now make the transfer instruction
var totalToksToSend = 0.0;
if (data.MultipleReceivers.Count > 0 && coppies == 0)
{
var index = 0;
foreach (var utxo in data.MultipleReceivers)
{
NTP1Instructions ti = new NTP1Instructions();
ti.amount = 1;
ti.vout_num = index;
TiList.Add(ti);
totalToksToSend++;
index++;
}
}
else if (data.MultipleReceivers.Count == 0 && coppies > 0)
{
for (var i = 0; i < coppies + 1; i++)
{
NTP1Instructions ti = new NTP1Instructions();
ti.amount = 1;
ti.vout_num = i;
TiList.Add(ti);
totalToksToSend++;
}
}
else if (data.MultipleReceivers.Count == 0 && coppies == 0)
{
NTP1Instructions ti = new NTP1Instructions();
ti.amount = 1;
ti.vout_num = 0;
TiList.Add(ti);
totalToksToSend++;
}
var metacomprimed = GetMetaComprimed(data.Metadata);
//Create the hex op_return
string ti_script = NTP1ScriptHelpers._NTP1CreateTransferScript(TiList, metacomprimed); //No metadata
var restOfToks = txres.Item2.Item2; //txres.Item2.Item2 holds all tokens in inputs tutxos
restOfToks -= totalToksToSend;
try
{
fee = CalcFee(transaction.Inputs.Count, 2, JsonConvert.SerializeObject(data.Metadata), true);
var balanceinSat = Convert.ToUInt64(allNeblInputCoins * FromSatToMainRatio);
if ((4 * MinimumAmount + fee) > balanceinSat)
throw new Exception("Not enought spendable Neblio on the address.");
var diffinSat = balanceinSat - Convert.ToUInt64(fee) - Convert.ToUInt64(MinimumAmount); // one MinimumAmount subtracted is because of OP_RETURN, others are subtracted below based on number of receivers
if (restOfToks > 0)
diffinSat -= Convert.ToUInt64(MinimumAmount);
if (receiverAddreses.Count > 0 && coppies == 0)
{
foreach (var receiver in receiverAddreses)
{
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), receiver.ScriptPubKey); // send to receiver NFT
}
}
else if (receiverAddreses.Count == 1 && coppies > 0)
{
for (var i = 0; i < coppies + 1; i++)
{
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), receiverAddreses.FirstOrDefault()?.ScriptPubKey); // send to receiver NFT
}
}
else if (receiverAddreses.Count == 0 && coppies > 0)
{
for (var i = 0; i < coppies + 1; i++)
{
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), addressForTx.ScriptPubKey); // send to receiver NFT
}
}
else
{
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), addressForTx.ScriptPubKey); // send to own NFT
}
var ti_b = NTP1ScriptHelpers.UnhexToByteArray(ti_script);
transaction.Outputs.Add(new TxOut()
{
Value = new Money(MinimumAmount),
ScriptPubKey = CreateOPRETURNScript(ti_b)
});
if (diffinSat > 0)
transaction.Outputs.Add(new Money(diffinSat), addressForTx.ScriptPubKey); // get diff back to sender address
if (restOfToks > 0) // just for minting new payment nft
transaction.Outputs.Add(new Money(MinimumAmount), addressForTx.ScriptPubKey); // add 10000 sat as carier of tokens which goes back
}
catch (Exception ex)
{
throw new Exception("Exception during adding outputs with payment in neblio." + ex.Message);
}
return transaction;
}
/// <summary>
/// Send Tokens to multiple receivers with different amounts of the tokens
/// </summary>
/// <param name="data">Mint data, please see SendTokenTxData class for the details</param>
/// <param name="coppies">0 or more coppies - with 0 input it is same as MintNFTTokenAsync</param>
/// <param name="ekey">Input EncryptionKey of the account</param>
/// <param name="nutxos">Optional input neblio utxo</param>
/// <param name="tutxos">Optional input token utxo</param>
/// <param name="multiTokens">If there is the multi token it needs to check if there is no conflict</param>
/// <returns>New Transaction Hash - TxId</returns>
public static async Task<Transaction> SendTokensToMultipleReceiversAsync(SendTokenTxData data, ICollection<Utxos> nutxos, ICollection<Utxos> tutxos, double fee = 20000)
{
if (data.Metadata == null || data.Metadata.Count == 0)
throw new Exception("Cannot send without metadata!");
List<BitcoinAddress> receiverAddreses = new List<BitcoinAddress>();
// load key and address
BitcoinAddress addressForTx;
addressForTx = BitcoinAddress.Create(data.SenderAddress, Network);
if (!string.IsNullOrEmpty(data.ReceiverAddress) || data.MultipleReceivers.Count > 0)
{
if (data.MultipleReceivers.Count == 0)
receiverAddreses.Add(BitcoinAddress.Create(data.ReceiverAddress, Network));
else
{
foreach (var a in data.MultipleReceivers)
receiverAddreses.Add(BitcoinAddress.Create(a.Address, Network));
}
}
var tutxo = tutxos.FirstOrDefault();
if (tutxo == null)
throw new Exception("Cannot send transaction, cannot load sender nebl utxo!");
var nutxo = nutxos.FirstOrDefault();
if (nutxo == null)
throw new Exception("Cannot send transaction, cannot load sender nebl utxo!");
var txres = GetTransactionWithNeblioAndTokensInputs(nutxos, tutxos, addressForTx);
var transaction = txres.Item1;
var allNeblInputCoins = txres.Item2.Item1;
List<NTP1Instructions> TiList = new List<NTP1Instructions>();
//Now make the transfer instruction
var totalToksToSend = 0.0;
if (data.MultipleReceivers.Count > 0)
{
var index = 0;
foreach (var rcv in data.MultipleReceivers)
{
NTP1Instructions ti = new NTP1Instructions();
ti.amount = (ulong)rcv.Amount;
ti.vout_num = index;
TiList.Add(ti);
totalToksToSend++;
index++;
}
}
else if (data.MultipleReceivers.Count == 0)
{
NTP1Instructions ti = new NTP1Instructions();
ti.amount = (ulong)data.Amount;
ti.vout_num = 0;
TiList.Add(ti);
totalToksToSend++;
}
var totalToksCheck = 0;
foreach (var t in TiList)
totalToksCheck += (int)t.amount;
if (data.Amount > 0 && totalToksCheck != data.Amount)
throw new Exception("Total amount of tokens in Transfer instructions to send is not equal to the amount of tokens to send!");
var metacomprimed = GetMetaComprimed(data.Metadata);
//Create the hex op_return
string ti_script = NTP1ScriptHelpers._NTP1CreateTransferScript(TiList, metacomprimed); //No metadata
var restOfToks = txres.Item2.Item2; //txres.Item2.Item2 holds all tokens in inputs tutxos
restOfToks -= totalToksToSend;
try
{
fee = CalcFee(transaction.Inputs.Count, 2, JsonConvert.SerializeObject(data.Metadata), true);
var balanceinSat = Convert.ToUInt64(allNeblInputCoins * FromSatToMainRatio);
if ((4 * MinimumAmount + fee) > balanceinSat)
throw new Exception("Not enought spendable Neblio on the address.");
var diffinSat = balanceinSat - Convert.ToUInt64(fee) - Convert.ToUInt64(MinimumAmount); // one MinimumAmount subtracted is because of OP_RETURN, others are subtracted below based on number of receivers
if (restOfToks > 0)
diffinSat -= Convert.ToUInt64(MinimumAmount);
if (receiverAddreses.Count > 0)
{
foreach (var receiver in receiverAddreses)
{
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), receiver.ScriptPubKey); // send to receiver NFT
}
}
else
{
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), addressForTx.ScriptPubKey); // send to own NFT
}
var ti_b = NTP1ScriptHelpers.UnhexToByteArray(ti_script);
transaction.Outputs.Add(new TxOut()
{
Value = new Money(MinimumAmount),
ScriptPubKey = CreateOPRETURNScript(ti_b)
});
if (diffinSat > 0)
transaction.Outputs.Add(new Money(diffinSat), addressForTx.ScriptPubKey); // get diff back to sender address
if (restOfToks > 0) // just for minting new payment nft
transaction.Outputs.Add(new Money(MinimumAmount), addressForTx.ScriptPubKey); // add 10000 sat as carier of tokens which goes back
}
catch (Exception ex)
{
throw new Exception("Exception during adding outputs with payment in neblio." + ex.Message);
}
return transaction;
}
/// <summary>
/// Wrap for SignAndBroadcast transaction function
/// </summary>
/// <param name="transaction"></param>
/// <param name="key"></param>
/// <returns></returns>
public static async Task<string> SignAndBroadcastTransaction(Transaction transaction, BitcoinSecret key)
{
return await SignAndBroadcast(transaction, key);
}
/// <summary>
/// Function will Split NTP1 tokens to smaller lots
/// receiver list - If you input 0, split will be done to sender address, if you input 1 receiver split will be done to receiver (all inputs)
/// if you will provide multiple receivers, the number of lots and receivers must match.
/// </summary>
/// <param name="receiver">List of receivers. </param>
/// <param name="lots"></param>
/// <param name="amount"></param>
/// <param name="tokenId"></param>
/// <param name="metadata"></param>
/// <param name="ekey">Input EncryptionKey of the account</param>
/// <param name="nutxos">Optional input neblio utxo</param>
/// <param name="tutxos">Optional input token utxo</param>
/// <returns>New Transaction Hash - TxId</returns>
public static async Task<Transaction> SplitNTP1TokensAsync(string address, List<string> receiver, int lots, int amount, string tokenId,
IDictionary<string, string> metadata,
ICollection<Utxos> nutxos,
ICollection<Utxos> tutxos)
{
List<BitcoinAddress> receiverAddreses = new List<BitcoinAddress>();
// load key and address
BitcoinSecret key;
BitcoinAddress addressForTx = BitcoinAddress.Create(address, Network);
if (receiver.Count > 0)
{
if (receiver.Count == 0)
{
receiverAddreses.Add(addressForTx);
}
else if (receiver.Count == 1)
{
var a = receiver.FirstOrDefault();
if (!string.IsNullOrEmpty(a))
receiverAddreses.Add(BitcoinAddress.Create(a, Network));
}
else
{
foreach (var a in receiver)
receiverAddreses.Add(BitcoinAddress.Create(a, Network));
}
}
if ((receiverAddreses.Count > 1 && lots > 1) && (receiverAddreses.Count != lots))
{
throw new Exception($"If you want to split coins to different receivers, the number of lots and receivers must match. Receivers {receiverAddreses.Count}, Lost {lots}. Some of input address may be wrong.");
}
var tutxo = tutxos.FirstOrDefault();
if (tutxo == null)
throw new Exception("Cannot send transaction, cannot load sender nebl utxo!");
var nutxo = nutxos.FirstOrDefault();
if (nutxo == null)
throw new Exception("Cannot send transaction, cannot load sender nebl utxo!");
var txres = GetTransactionWithNeblioAndTokensInputs(nutxos, tutxos, addressForTx);
var transaction = txres.Item1;
var allNeblInputCoins = txres.Item2.Item1;
if (metadata == null)
metadata = new Dictionary<string, string>();
metadata.Add("TransactionType", "Token Split");
List<NTP1Instructions> TiList = new List<NTP1Instructions>();
//Now make the transfer instruction
var totalToksToSend = 0.0;
if (receiverAddreses.Count > 0)
{
var index = 0;
foreach (var add in receiverAddreses)
{
NTP1Instructions ti = new NTP1Instructions();
ti.amount = (ulong)amount;
ti.vout_num = index;
TiList.Add(ti);
totalToksToSend += amount;
index++;
}
}
else if (receiverAddreses.Count == 0 || lots > 1)
{
for (var i = 0; i < lots; i++)
{
NTP1Instructions ti = new NTP1Instructions();
ti.amount = (ulong)amount;
ti.vout_num = i;
TiList.Add(ti);
totalToksToSend += amount;
}
}
var metacomprimed = GetMetaComprimed(metadata);
//Create the hex op_return
string ti_script = NTP1ScriptHelpers._NTP1CreateTransferScript(TiList, metacomprimed); //No metadata
var restOfToks = txres.Item2.Item2; //txres.Item2.Item2 holds all tokens in inputs tutxos
restOfToks -= totalToksToSend;
try
{
var fee = CalcFee(transaction.Inputs.Count, 2, JsonConvert.SerializeObject(metadata), true);
var balanceinSat = Convert.ToUInt64(allNeblInputCoins * FromSatToMainRatio);
if ((4 * MinimumAmount + fee) > balanceinSat)
throw new Exception("Not enought spendable Neblio on the address.");
var diffinSat = balanceinSat - Convert.ToUInt64(fee) - Convert.ToUInt64(MinimumAmount); // one MinimumAmount subtracted is because of OP_RETURN, others are subtracted below based on number of receivers
if (restOfToks > 0)
diffinSat -= Convert.ToUInt64(MinimumAmount);
if (receiverAddreses.Count > 0)
{
foreach (var recv in receiverAddreses)
{
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), recv.ScriptPubKey); // send to receiver
}
}
else if (receiverAddreses.Count == 1)
{
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), receiverAddreses[0].ScriptPubKey); // send to receiver
}
else
{
for (var i = 0; i < lots; i++)
{
diffinSat -= Convert.ToUInt64(MinimumAmount);
transaction.Outputs.Add(new Money(MinimumAmount), addressForTx.ScriptPubKey); // send to own
}
}
var ti_b = NTP1ScriptHelpers.UnhexToByteArray(ti_script);
transaction.Outputs.Add(new TxOut()
{
Value = new Money(MinimumAmount),
ScriptPubKey = CreateOPRETURNScript(ti_b)
});
if (diffinSat > 0)
transaction.Outputs.Add(new Money(diffinSat), addressForTx.ScriptPubKey); // get diff back to sender address
if (restOfToks > 0) // just for minting new payment nft
transaction.Outputs.Add(new Money(MinimumAmount), addressForTx.ScriptPubKey); // add 10000 sat as carier of tokens which goes back
}
catch (Exception ex)
{
throw new Exception("Exception during adding outputs with payment in neblio." + ex.Message);
}
return transaction;
}
/// <summary>
/// Function will sent exact NFT.
/// You must fill the input token utxo in data object!
/// </summary>
/// <param name="data">Send data, please see SendTokenTxData class for the details</param>
/// <param name="nutxos">Optional input neblio utxo</param>
/// <returns>New Transaction Hash - TxId</returns>