-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmicrogrid-dapp.cs
1675 lines (1350 loc) · 71.2 KB
/
microgrid-dapp.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 Neo.SmartContract.Framework;
using Neo.SmartContract.Framework.Services.Neo;
using Neo.SmartContract.Framework.Services.System;
using System;
using System.ComponentModel;
using System.Numerics;
namespace Neo.SmartContract
{
public class MTEsm : Framework.SmartContract
{
//---------------------------------------------------------------------------------------------
// EVENTS
[DisplayName("transaction")]
public static event Action<byte[], byte[], BigInteger, BigInteger> Transfer;
[DisplayName("transaction")]
public static event Action<string, byte[], BigInteger, BigInteger> Retract;
[DisplayName("membership")]
public static event Action<byte[], string> Membership;
[DisplayName("process")]
public static event Action<string, string> Process;
[DisplayName("ballot")]
public static event Action<string, byte[], bool> Ballot;
[DisplayName("offer")]
public static event Action<string, byte[], BigInteger> Offer;
[DisplayName("change")]
public static event Action<string, object> Update;
[DisplayName("invalid operation")]
public static event Action<string> Exception;
//---------------------------------------------------------------------------------------------
// GLOBAL VARIABLES
// The total number of referendum processes.
private static BigInteger NumOfRef() => Storage.Get("numofref").AsBigInteger();
// The total number of power plant (PP) units.
private static BigInteger NumOfPP() => Storage.Get("numofpp").AsBigInteger();
// The total number of members.
private static BigInteger NumOfMemb() => Storage.Get("numofmemb").AsBigInteger();
// The group total power supply, i.e., sum of PP's capacity.
private static BigInteger TotalSupply() => Storage.Get("totalsupply").AsBigInteger();
// The member's dataset settings.
private static string[] profile => new string[] {"fullname", "utility"};
private static string[] register => new string[] {"quota", "tokens"};
private struct MemberData
{
public static StorageMap ID => Storage.CurrentContext.CreateMap(nameof(ID));
public static StorageMap FullName => Storage.CurrentContext.CreateMap(nameof(FullName));
public static StorageMap Utility => Storage.CurrentContext.CreateMap(nameof(Utility));
public static StorageMap Quota => Storage.CurrentContext.CreateMap(nameof(Quota));
public static StorageMap Tokens => Storage.CurrentContext.CreateMap(nameof(Tokens));
}
// The referendum's dataset settings.
private struct RefData
{
public static StorageMap ID => Storage.CurrentContext.CreateMap(nameof(ID));
public static StorageMap Proposal => Storage.CurrentContext.CreateMap(nameof(Proposal));
public static StorageMap Notes => Storage.CurrentContext.CreateMap(nameof(Notes));
public static StorageMap Cost => Storage.CurrentContext.CreateMap(nameof(Cost));
public static StorageMap Address => Storage.CurrentContext.CreateMap(nameof(Address));
public static StorageMap Time => Storage.CurrentContext.CreateMap(nameof(Time));
public static StorageMap MoneyRaised => Storage.CurrentContext.CreateMap(nameof(MoneyRaised));
public static StorageMap NumOfVotes => Storage.CurrentContext.CreateMap(nameof(NumOfVotes));
public static StorageMap CountTrue => Storage.CurrentContext.CreateMap(nameof(CountTrue));
public static StorageMap Outcome => Storage.CurrentContext.CreateMap(nameof(Outcome));
public static StorageMap HasResult => Storage.CurrentContext.CreateMap(nameof(HasResult));
public static StorageMap StartTime => Storage.CurrentContext.CreateMap(nameof(StartTime));
public static StorageMap EndTime => Storage.CurrentContext.CreateMap(nameof(EndTime));
}
// The PP's dataset settings.
private struct PPData
{
public static StorageMap ID => Storage.CurrentContext.CreateMap(nameof(ID));
public static StorageMap Capacity => Storage.CurrentContext.CreateMap(nameof(Capacity));
public static StorageMap Cost => Storage.CurrentContext.CreateMap(nameof(Cost));
public static StorageMap Utility => Storage.CurrentContext.CreateMap(nameof(Utility));
public static StorageMap TimeToMarket => Storage.CurrentContext.CreateMap(nameof(TimeToMarket));
public static StorageMap NumOfFundMemb => Storage.CurrentContext.CreateMap(nameof(NumOfFundMemb));
public static StorageMap HasStarted => Storage.CurrentContext.CreateMap(nameof(HasStarted));
}
// The ICO's dataset settings (for crowdfunding).
private struct ICOData
{
public static StorageMap StartTime => Storage.CurrentContext.CreateMap(nameof(StartTime));
public static StorageMap EndTime => Storage.CurrentContext.CreateMap(nameof(EndTime));
public static StorageMap TotalAmount => Storage.CurrentContext.CreateMap(nameof(TotalAmount));
public static StorageMap Contributions => Storage.CurrentContext.CreateMap(nameof(Contributions));
public static StorageMap Success => Storage.CurrentContext.CreateMap(nameof(Success));
public static StorageMap HasResult => Storage.CurrentContext.CreateMap(nameof(HasResult));
public static StorageMap Bid => Storage.CurrentContext.CreateMap(nameof(Bid));
}
// The predefined periods to answer both a referendum and a crowdfunding, and to wait until a PP construction.
private const uint timeFrameRef = 120; // 30 days = 2592000
private const uint timeFrameCrowd = 5184000; // 60 days
private const uint minTimeToMarket = 2592000; // 30 days
// The essential settings to support the process of a new PP crowdfunding.
private const int minOffer = 100; // Brazilian Reais (R$)
private const uint factor = 1000; // 1kW == 1SEB
// The token basic settings.
private static string Name() => "Sharing Electricity in Brazil";
private static string Symbol() => "SEB";
// The power limits of the distributed generation category defined by Brazilian law (from 0MW to 5MW).
private static int[] PowGenLimits() => new int[] {0, 5000000};
// The time a given function is invoked.
private static uint InvokedTime() => Blockchain.GetHeader(Blockchain.GetHeight()).Timestamp;
// The trick to lock the admission operation process without a referendum.
private static void OnlyOnce() => Storage.Put("firstcall", 1);
// The trick to support the conversion from 'int' to 'string'.
private static string[] Digits() => new string[10] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
// The characters of the Base58 scheme.
private const string Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
//---------------------------------------------------------------------------------------------
// THE MAIN INTERFACE
public static object Main ( byte[] address, string operation, params object[] args )
{
// General operation.
if ( operation == "admission" )
{
if ( args.Length != 2 )
return Warning("Please provide the 2 arguments: your full name, and the power utility name.");
if ( !Runtime.CheckWitness(address) )
return Warning("The admission can not be done on someone else's behalf.");
if ( ( (string)GetMemb(address) ).Length != 0 )
return Warning("Thanks, you're already a member. We're glad to have you as part of the group!");
if ( Storage.Get("firstcall").AsBigInteger() == 0 )
{
// No admission process is required.
// Locks this 'if' statement.
OnlyOnce();
// Defines the 'invoker/caller' as the first member.
Membership( address, "Welcome on board!" );
Member( address, (string)args[0], (string)args[1], 0, 0 );
return true;
}
return Admission( address, // invoker/caller address
(string)args[0], // fullName
(string)args[1] ); // utility
}
if ( operation == "admission war" )
{
return RefWar( (string)args[2], // rID
(string)args[0], // fullName
(string)args[1], // utility
address ); // invoker/caller address
}
// Partially restricted operation.
if ( operation == "summary" )
{
if ( args.Length < 1 )
return Warning("Provide at least a member address or a PP ID.");
if ( ((string)GetMemb((byte[])args[0])).Length != 0 )
{
// The args[0] is a member, i.e.,
// it has being requested information about a member.
if ( !Runtime.CheckWitness(address) )
return Warning("This request can not be done on someone else's behalf.");
if ( ((string)GetMemb(address)).Length == 0 )
return Warning();
}
return Summary( (object)args[0], // any ID
(string)args[1] ); // desired option
}
// Restricted operations.
if ( ((string)GetMemb(address)).Length != 0 )
{
// Group operations.
if ( operation == "vote" )
{
if ( args.Length != 2 )
return Warning("Please provide the 2 arguments: the referendum ID, and your vote.");
if ( !Runtime.CheckWitness(address) )
return Warning("The vote can not be done on someone else's behalf.");
if ( isLock( (string)args[0]) )
return Warning("The ballot has ended.");
return Vote( (string)args[0], // referendum ID
address, // member address
(bool)args[1] ); // vote answer
}
if ( operation == "bid" )
{
if ( args.Length != 2 )
return Warning("Please provide the 2 arguments: the PP ID, and your bid.");
if ( !Runtime.CheckWitness(address) )
return Warning("The bid can not be done on someone else's behalf.");
if ( (((string)args[0])[0] != 'P') || (((string)args[0]).Length == 0) )
return Warning("Provide a valid PP ID.");
if ( (GetPP((string)args[0], "utility")) != (GetMemb(address, "utility")) )
return Warning("This member cannot profit from this power utility." );
if ( (int)args[1] <= minOffer )
return Warning(String.Concat("The minimum bid allowed is R$ ", Int2Str(minOffer)));
if ( isLock( (string)args[0] ) )
return Warning("The crowdfunding has ended.");
return Bid( (string)args[0], // PP ID
address, // member address
(BigInteger)args[1] ); // bid value
}
if ( operation == "change" )
{
if ( args.Length != 2 )
return Warning("Please provide 2 arguments only. The first one must be either the identification of the member (address) or the PP (ID). The second one must be an array. It can be either the options about the data that will be changed, or an empty array to request the deletion of something.");
// To simplify the indexing.
var opt = (object[])args[1];
// Should be a PP ID.
if ( IsValidId(args[0]) )
{
if ( ((string)GetPP((string)args[0], "utility")).Length == 0 )
return Warning("Provide a valid PP ID.");
if ( opt.Length != 1 )
return Warning("Only one option is required to update a PP subject. It can be a PP utility name, or a new bid value for a PP crowdfunding campaign.");
// It should be a 'BigInteger'.
if ( IsValidNum(opt[0]) )
{
if ( isLock( (string)args[0] ) )
return Warning("The crowdfunding has ended.");
if ( !(Runtime.CheckWitness(address)) )
return Warning("Only the member can change its bid.");
// Updates the option array to pass the 'address' together with the bid value.
int i = opt.Length;
object[] option = new object[i+1];
while( i > 0 )
{
option[i] = opt[i-1];
i--;
}
option[i] = address;
return Change( (object)args[0], // PP ID
option ); // array with desired values
}
}
// Should be a member ID (address).
else
{
if ( ((string)GetMemb((byte[])args[0])).Length == 0 )
return Warning("Provide a valid member address.");
if ( (opt.Length != 2) & (opt.Length != 0) )
return Warning("Provide valid arguments to update/delete an address.");
if ( ( ((string)opt[0] == profile[0]) | ((string)opt[0] == profile[1]) ) & !(Runtime.CheckWitness(address)) )
return Warning("Only the member can change her/his profile data.");
}
return Change( (object)args[0], // member address or PP ID
opt ); // array with desired values
}
if ( operation == "change war" )
{
return RefWar( (string)args[2], // rID
"Change register_", // proposal
(string)args[0], // register variable = "quota"
address, // member ID
(int)args[1] ); // new quota value
}
if ( operation == "power up" )
{
if ( args.Length != 4 )
return Warning("Please provide the 4 arguments: the PP capacity, the cost to build it up, the power utility name in which the PP will be connected to, and the period to wait until the new PP gets ready to operate.");
if ( ((int)args[3] == 0) || ((int)args[3] < minTimeToMarket) )
return Warning("The time to market must be a factual period.");
return PowerUp( (int)args[0], // capacity [MW]
(int)args[1], // cost [R$]
(string)args[2], // power utility name
(uint)args[3] ); // time to market
}
if ( operation == "trade" )
{
if ( args.Length != 3 )
return Warning("Please provide the 3 arguments: the address of who you are transacting to, the quota value, and the amount of tokens.");
if ( !Runtime.CheckWitness(address) )
return Warning("Only the owner of an account can exchange her/his asset.");
if ( ((string)GetMemb((byte[])args[0])).Length == 0 )
return Warning("The address you are transacting to must be a member too.");
if ( (GetMemb(address, "utility")) != (GetMemb((byte[])args[0], "utility")) )
return Warning("Both members must belong to the same power utility coverage area.");
if ( ((int)args[1] <= 0) & ((int)args[2] <= 0) )
return Warning("You're doing it wrong. To donate energy let ONLY the 3rd argument empty. Otherwise, to donate tokens let ONLY the 2nd argument empty.");
return Trade( address, // from address
(byte[])args[0], // to address
(BigInteger)args[1], // quota exchange
(BigInteger)args[2] ); // token price
}
// Administrative operations.
if ( operation == "admission result" )
{
if ( args.Length != 1 )
return Warning("Please provide only the admission process ID.");
if ( isLock( (string)args[0], "inv" ) )
return Warning("There isn't a result yet.");
return AdmissionResult( (string)args[0] ); // Referendum ID
}
if ( operation == "admission result war" )
{
return AdmissionResultWar( (string)args[0] ); // Referendum ID
}
if ( operation == "change result" )
{
if ( args.Length != 1 )
return Warning("Please provide only the change process ID.");
if ( isLock( (string)args[0], "inv" ) )
return Warning("There isn't a result yet.");
return ChangeResult( (string)args[0] ); // Referendum ID
}
if ( operation == "power up result" )
{
if ( args.Length == 0 )
return Warning("Please provide at least the new PP process ID.");
if ( args.Length > 2 )
return Warning("Please provide at most the new PP process ID, and the PP ID itself if any.");
return PowerUpResult( (string)args[0], // Referendum ID
(string)args[1] ); // PP ID
}
if ( operation == "list of power plants" )
{
if ( args.Length != 0 )
return Warning("This function does not need attributes.");
return ListOfPPs();
}
if ( operation == "list of members" )
{
if ( args.Length != 0 )
return Warning("This function does not need attributes.");
return ListOfMembers();
}
}
return Warning("No operation found. Have you written it right?");
}
//---------------------------------------------------------------------------------------------
// GROUP FUNCTIONS - The restrictions are made on the 'Main'.
// To request to join the group.
private static string Admission( byte[] address, string fullName, string utility )
{
string rID = Ref( fullName, utility, address );
Membership( address, "Request for admission." );
return rID;
}
// To get information about something.
private static object Summary( object id, string opt = null )
{
// If 'id' is a 'byte[]' == member.
if ( ((byte[])id).Length == 20 )
{
var address = (byte[])id;
if ( (opt == "") || (opt == "detailed") )
{
object[] brief = new object[] { GetMemb(address), GetMemb(address,"utility"), GetMemb(address,"quota"), GetMemb(address,"tokens") };
if ( opt == "detailed" )
{
ShowContributedValues( address, ListOfPPs() );
}
return brief;
}
return GetMemb(address, opt);
}
// If 'id' is a 'string' with prefix 'P' == power plant.
else if ( ((string)id)[0] == 'P' )
{
var ppID = (string)id;
// The PP's crowdfunding had succeed and the PP is operating.
if ( (bool)GetPP(ppID) )
{
if ( (opt == "") || (opt == "detailed") )
{
object[] brief = new object[] { GetPP(ppID,"capacity"), GetPP(ppID,"cost"), GetPP(ppID,"utility"), GetPP(ppID,"numoffundmemb") };
if ( opt == "detailed" )
{
ShowContributedValues( ppID, ListOfMembers() );
}
return brief;
}
return GetPP(ppID, opt);
}
// The PP's crowdfunding may be succeed or not, and the PP is definitely not operating.
else
{
if ( (opt == "") || (opt == "detailed") )
{
object[] brief = new object[] { GetCrowd(ppID,"starttime"), GetCrowd(ppID,"endtime"), GetCrowd(ppID,"totalamount"), GetCrowd(ppID,"contributions"), GetCrowd(ppID,"success") };
if ( opt == "detailed" )
{
foreach ( byte[] member in ListOfMembers() )
{
BigInteger bid = GetBid(ppID, member);
if ( bid != 0 )
{
Runtime.Notify( new object[] { member, bid } );
}
}
}
return brief;
}
return GetCrowd(ppID, opt);
}
}
// If 'id' is a 'string' with prefix 'R' == referendum process.
else if ( ((string)id)[0] == 'R' )
{
var rID = (string)id;
if ( opt == "" )
{
return new object[] { GetRef(rID,"proposal"), GetRef(rID,"notes"), GetRef(rID,"cost"), GetRef(rID,"outcome") };
}
return GetRef(rID, opt);
}
// Wrap-up the group information.
else
{
return new object[] { PowGenLimits()[0], PowGenLimits()[1], NumOfPP(), NumOfMemb(), Name(), Symbol(), TotalSupply() };
}
}
// To vote in a given process.
private static bool Vote( string rID, byte[] member, bool answer )
{
// Increases the number of votes.
BigInteger temp = (BigInteger)GetRef(rID,"numofvotes");
UpRef(rID, "numofvotes", temp+1);
if ( answer )
{
// Increases the number of "trues".
temp = (BigInteger)GetRef(rID,"counttrue");
UpRef(rID, "counttrue", temp+1);
}
// Publishes the vote.
Ballot(rID, member, answer);
return true;
}
// To make a bid in a new PP crowdfunding process.
private static bool Bid( string ppID, byte[] member, BigInteger bid )
{
BigInteger target = (BigInteger)GetPP(ppID, "cost");
BigInteger funds = (BigInteger)GetCrowd(ppID, "totalamount");
if ( bid > (target - funds) )
return Warning( String.Concat(String.Concat("You offered more than the amount available (R$ ", Int2Str((int)(target - funds)) ), ",00). Bid again!" ));
// WARNING!
// All the following steps are part of a crowdfunding process.
// Although the PP already has a register (i.e. a PP ID),
// it does not have started to operate (PPData.HasStarted = false).
// Increases the value gathered so far.
UpCrowd(ppID, "totalamount", funds + bid);
// Increases the number of contributions.
BigInteger temp = (BigInteger)GetCrowd(ppID, "contributions");
UpCrowd(ppID, "contributions", temp+1);
// Tracks bid by member for each ICO process.
UpBid(ppID, member, bid);
Offer(ppID, member, bid);
return true;
// If the whole fund process succeed, the money bid must be converted to percentage (bid/cost),
// so it will be possible to define the quota and the SEB a member has to gain.
// This is made on PowerUpResult(...).
}
// To update a member or a PP dataset on the ledger.
private static object Change( object id, params object[] opts )
{
// A referendum must start in case the change needs group's consensus.
string rID;
// If 'id' is a 'byte[]' == member.
if ( ((byte[])id).Length == 20 )
{
if ( opts.Length != 0 )
{
// Only the member can change its own personal data.
// To UPDATE, the params must be ['profile option', 'value'].
if ( !IsValidNum(opts[1]) )
{
UpMemb((byte[])id, (string)opts[0], (string)opts[1]);
Update("Profile data.", id);
return true;
}
// Any member can request the change of registration data of other member.
// To UPDATE, the params must be ['register option', 'value'].
rID = Ref( "Change register_", (string)opts[0], (byte[])id, (int)opts[1] );
Process( rID, "Request the change of a member's registration data." );
return rID;
}
// else
// Any member can request to delete another member.
rID = Ref( "Delete member_", null, (byte[])id );
Process(rID, "Request to dismiss a member.");
return rID;
}
// Otherwise, the 'id' is a 'string' with prefix 'P' == power plant.
// Only the member can change its own bid.
// To UPDATE, the params must be ['address', 'new bid value'].
if ( opts.Length == 2 )
{
UpBid((string)id, (byte[])opts[0], (BigInteger)opts[1]);
Update("Bid.", id);
return true;
}
// Any member can request the change of the 'utility' a PP belongs to.
// To UPDATE, the params must be ['new utility name'].
if ( opts.Length == 1 )
{
rID = Ref( "Change utility_", (string)opts[0], ((string)id).AsByteArray() );
Process( rID, "Request the change of a PP's utility name." );
return rID;
}
// Any member can request to DELETE a PP.
// The 'opts.Length' is empty.
rID = Ref("Delete PP_", null, ((string)id).AsByteArray());
Process(rID, "Request to delete a PP.");
return rID;
}
// To integrate a new PP on the group power generation.
private static string PowerUp( int capacity, int cost, string utility, uint timeToMarket )
{
string rID = Ref( Int2Str(capacity), utility, "".AsByteArray(), cost, timeToMarket );
Process( rID, "Request to add a new PP." );
return rID;
}
// To allow the transfer of shares/tokens from someone to someone else (transactive energy indeed).
// The 'fromAddress' will exchange an amount of shares with 'toAddress' by a defined token price,
// i.e., while 'fromAddress' sends shares to 'toAddress', the 'toAddress' sends tokens to 'fromAddress'.
private static bool Trade( byte[] fromAddress, byte[] toAddress, BigInteger exchange, BigInteger price )
{
int n = 2;
BigInteger[] toWallet = new BigInteger[n];
BigInteger[] fromWallet = new BigInteger[n];
for ( int r = 0; r < n; r++ )
{
// Remember: register = {"quota", "tokens"}.
fromWallet[r] = (BigInteger)GetMemb( fromAddress, register[r] );
toWallet[r] = (BigInteger)GetMemb( toAddress, register[r] );
}
if ( ( fromWallet[0] < exchange ) || ( toWallet[1] < price ) ) return false;
UpMemb(fromAddress, register[0], fromWallet[0] - exchange);
UpMemb(toAddress, register[0], toWallet[0] + exchange);
UpMemb(toAddress, register[1], toWallet[1] - price);
UpMemb(fromAddress, register[1], fromWallet[1] + price);
Transfer(fromAddress, toAddress, exchange, price);
return true;
}
//---------------------------------------------------------------------------------------------
// ADMINISTRATIVE FUNCTIONS
// After a period of 'timeFrameRef' days, a member should invoke the below functions to state
// the referendum process. An off-chain operation should handle this waiting time.
private static bool AdmissionResult( string rID )
{
// Calculates the result.
CalcResult(rID);
// Retrives the address from private storage.
byte[] address = (byte[])GetRef(rID, "address");
if ( Str2Bool( (string)GetRef(rID, "outcome") ) )
{
// Retrives the member data from private storage.
// string fullName = (string)GetRef(rID, "proposal");
// string utility = (string)GetRef(rID, "notes");
// Adds a new member after the group approval.
// Member( address, fullName, utility, 0, 0 );
// Membership( address, "Welcome on board!" );
// Wait for the second step.
return true;
}
// Otherwise, leave the user out of the group.
Membership( address, "Not approved yet." );
DelMemb( address );
return false;
}
private static bool AdmissionResultWar( string rID )
{
// Retrives the address from private storage.
byte[] address = (byte[])GetRef(rID, "address");
// Retrives the member data from private storage.
string fullName = (string)GetRef(rID, "proposal");
string utility = (string)GetRef(rID, "notes");
// Adds a new member after the group approval.
Member( address, fullName, utility, 0, 0 );
Membership( address, "Welcome on board!" );
return true;
}
private static bool ChangeResult( string rID )
{
// Calculates the result.
CalcResult(rID);
if ( Str2Bool( (string)GetRef(rID, "outcome") ) )
{
Process(rID, "Approved.");
// Identifies the proposal and does the respective operation.
string proposal = (string)GetRef(rID, "proposal");
byte[] key;
if ( proposal == "Change register_" )
{
key = (byte[])GetRef(rID, "address");
UpMemb(key, (string)GetRef(rID, "notes"), (BigInteger)GetRef(rID, "cost"));
Update("Registration data.", key);
}
if ( proposal == "Delete member_" )
{
key = (byte[])GetRef(rID, "address");
BigInteger portion = (BigInteger)GetMemb(key, "quota");
BigInteger give_out = portion/(NumOfMemb() - 1);
foreach ( byte[] member in ListOfMembers() )
{
// In an infinitesimal period of time the group will be disbalanced
// until the related member be completely deleted.
// There is no side effect on power distribution, and
// it is better than iterate through each member.
Distribute(member, give_out, 0);
}
DelMemb(key);
Membership(key, "Goodbye.");
}
if ( proposal == "Change utility_" )
{
UpPP(rID, "utility", (string)GetRef(rID, "notes"));
Update("Belonging of.", rID);
}
if ( proposal == "Delete PP_" )
{
DelPP(rID);
Update("Deletion of.", rID);
}
return true;
}
Process(rID, "Denied.");
return false;
}
private static object PowerUpResult( string rID, string ppID = null )
{
// STEP 1 - Analyzes the referendum about the request for a new PP.
if ( ppID == null )
{
if ( isLock(rID, "inv") )
return Warning("There isn't a result about the new PP request yet.");
// After the 'timeFrameRef' waiting period...
// Evaluates the referendum result only once.
if ( (BigInteger)GetRef(rID) == 0 )
{
// Updates the result.
CalcResult(rID);
if ( Str2Bool( (string)GetRef(rID, "outcome") ) )
{
// Referendum has succeeded. It's time to register a new PP.
// Gets the terms from the begining of the process.
string capacity = (string)GetRef(rID, "proposal");
BigInteger cost = (BigInteger)GetRef(rID, "cost");
string utility = (string)GetRef(rID, "notes");
uint timeToMarket = (uint)GetRef(rID, "time");
// Generates the PP ID.
string PPid = PP(capacity, cost, utility, timeToMarket);
// Starts to raise money for it.
CrowdFunding(PPid);
Process(PPid, "Shut up and give me money!");
return PPid;
}
// Otherwise, the referendum of the PP request (Ref ID) continues registered
// in the group space, however it does not have a register (PP ID).
Process(rID, "This PP was not approved yet. Let's wait a bit more.");
return false;
}
return "This process step is completed.";
}
// STEP 2 - Analyzes the crowdfunding of the new PP approved.
if ( isLock(ppID, "inv") )
return Warning("There isn't a result about the new PP crowdfunding yet.");
// After the 'timeFrameCrowd' waiting period...
// Keeps the value for the following operations handy.
BigInteger target = (BigInteger)GetPP(ppID, "cost");
// Evaluates the crowdfunding result only once.
if ( (BigInteger)GetCrowd(ppID) == 0 )
{
// Updates the result.
UpCrowd(ppID, "hasresult", 1);
// Gets the value from the crowdfunding process.
BigInteger funding = (BigInteger)GetCrowd(ppID, "totalamount");
// Evaluates if the building of the new PP starts or not.
if ( funding == target )
{
// Crowdfunding has succeeded.
UpCrowd(ppID, true);
// Updates the number of investors.
UpPP(ppID, "numOfFundMemb", ListOfFunders(ppID).Length);
Process(ppID, "New power plant on the way.");
return true;
}
// Otherwise, the "success" remains as 'false'.
foreach ( byte[] funder in ListOfFunders(ppID) )
{
Cancel(ppID, funder);
}
Process(ppID, "Fundraising has failed.");
return false;
}
// STEP 3 - Analyzes the PP operation status.
// Calculates the date the new PP is planned to start to operate,
// that can be always updated until the deadline.
// operationDate = ICO_endTime + PP_timeToMarket
uint operationDate = (uint)GetCrowd(ppID, "endtime") + (uint)GetPP(ppID, "timetomarket");
if ( InvokedTime() <= operationDate )
return Warning("The new PP is not ready to operate yet.");
// After waiting for the time to market...
// Evaluates the construction only once.
if ( (BigInteger)GetPP(ppID) == 0 )
{
// When the PP is ready to operate, it's time to distribute tokens and shares.
// Increases the total power supply of the group.
BigInteger capOfPP = (BigInteger)GetPP(ppID, "capacity"); // [MW]
BigInteger capOfGroup = TotalSupply() + capOfPP; // [MW]
Storage.Put("totalsupply", capOfGroup);
// Identifies how much the new PP takes part on the group total power supply.
BigInteger sharesOfPP = capOfPP/capOfGroup; // [pu]
foreach ( byte[] funder in ListOfFunders(ppID) )
{
// Gets the member contribution.
BigInteger grant = GetBid(ppID, funder); // [R$]
// Identifies the member participation rate.
BigInteger rate = grant/target; // [pu]
// Defines how much of crypto-currency a member acquires from the new PP's capacity.
BigInteger tokens = (rate * capOfPP)/factor; // [MW/1000 = kW == SEB]
// Defines how much of energy a member is entitled over the total power supply.
BigInteger quota = rate * sharesOfPP * capOfGroup; // [MW]
// Updates the member register data.
Distribute(funder, quota, tokens);
}
// Updates the result.
UpPP(ppID, "hasstarted", 1);
Process(ppID, "A new power plant is now operating.");
return true;
}
return "There is nothing more to be done.";
}
// To return the IDs of each PP.
private static byte[][] ListOfPPs()
{
byte[][] ppIDs = new byte[ (int)NumOfPP() ][];
for ( int num = 0; num < NumOfPP(); num++ )
{
ppIDs[num] = PPData.ID.Get( Int2Str(num+1) );
}
return ppIDs;
}
// To return the address of each member.
private static byte[][] ListOfMembers()
{
byte[][] addresses = new byte[ (int)NumOfMemb() ][];
for ( int num = 0; num < NumOfMemb(); num++ )
{
addresses[num] = MemberData.ID.Get( Int2Str(num+1) );
}
return addresses;
}
// To return a list of members that have financed a given PP.
private static byte[][] ListOfFunders( string ppID )
{
byte[][] funders = new byte[ (int)GetCrowd(ppID, "contributions") ][];
BigInteger bid;
int num = 0;
foreach ( byte[] member in ListOfMembers() )
{
bid = GetBid( ppID, member );
if ( bid != 0 )
{
funders[num] = member;
num++;
}
}
return funders;
}
//---------------------------------------------------------------------------------------------
// SYSTEM FUNCTIONS
// A new PP will only distribute tokens and shares after a
// crowdfunding process succeed and the PP starts to operate.
// All the exceptions were handle during the crowdfunding.
// Now, it only needs to distribute the assets.
private static void Distribute( byte[] toAddress, BigInteger quota, BigInteger tokens )
{
BigInteger[] pastWallet = new BigInteger[ register.Length ];
int num = 0;
// Remember: register = {"quota", "tokens"}.
foreach ( string data in register )
{
pastWallet[num] = ( (BigInteger)GetMemb(toAddress, data) );
num++;
}
UpMemb(toAddress, register[0], pastWallet[0] + quota);
UpMemb(toAddress, register[1], pastWallet[1] + tokens);
Transfer(null, toAddress, quota, tokens);
}
// To create a custom ID of a process based on its particular specifications.
private static string ID( string prefix, bool unique, params string[] args )
{
// Assuming that all operations are little-endian.
// STEP 1 - Creates the hash.
string data = null;
if ( unique ) data = Int2Str((int)InvokedTime());
foreach ( string a in args )
{
data = String.Concat(data,a);
}
byte[] scriptHash = Hash160( data.AsByteArray() ); // length = 20 bytes
// STEP 2 - Enlarges the array to get the desired BigInteger's numbers range.
byte[] temp = scriptHash.Take(1);
scriptHash = scriptHash.Concat(temp); // length = 21 bytes
// STEP 3 - Adds the prefix.
byte[] preID = scriptHash.Concat( prefix.AsByteArray() ); // length = 22 bytes
// STEP 3 - Converts to Base58.
return Encode58( preID );
}