-
Notifications
You must be signed in to change notification settings - Fork 14
/
eosio.system.hpp
1554 lines (1367 loc) · 83.7 KB
/
eosio.system.hpp
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
#pragma once
#include <eosio/asset.hpp>
#include <eosio/binary_extension.hpp>
#include <eosio/privileged.hpp>
#include <eosio/producer_schedule.hpp>
#include <eosio/singleton.hpp>
#include <eosio/system.hpp>
#include <eosio/time.hpp>
#include <eosio.system/exchange_state.hpp>
#include <eosio.system/native.hpp>
#include <deque>
#include <optional>
#include <string>
#include <type_traits>
#ifdef CHANNEL_RAM_AND_NAMEBID_FEES_TO_REX
#undef CHANNEL_RAM_AND_NAMEBID_FEES_TO_REX
#endif
// CHANNEL_RAM_AND_NAMEBID_FEES_TO_REX macro determines whether ramfee and namebid proceeds are
// channeled to REX pool. In order to stop these proceeds from being channeled, the macro must
// be set to 0.
#define CHANNEL_RAM_AND_NAMEBID_FEES_TO_REX 1
namespace eosiosystem {
using eosio::asset;
using eosio::binary_extension;
using eosio::block_timestamp;
using eosio::check;
using eosio::const_mem_fun;
using eosio::datastream;
using eosio::indexed_by;
using eosio::name;
using eosio::same_payer;
using eosio::symbol;
using eosio::symbol_code;
using eosio::time_point;
using eosio::time_point_sec;
using eosio::unsigned_int;
inline constexpr int64_t powerup_frac = 1'000'000'000'000'000ll; // 1.0 = 10^15
template<typename E, typename F>
static inline auto has_field( F flags, E field )
-> std::enable_if_t< std::is_integral_v<F> && std::is_unsigned_v<F> &&
std::is_enum_v<E> && std::is_same_v< F, std::underlying_type_t<E> >, bool>
{
return ( (flags & static_cast<F>(field)) != 0 );
}
template<typename E, typename F>
static inline auto set_field( F flags, E field, bool value = true )
-> std::enable_if_t< std::is_integral_v<F> && std::is_unsigned_v<F> &&
std::is_enum_v<E> && std::is_same_v< F, std::underlying_type_t<E> >, F >
{
if( value )
return ( flags | static_cast<F>(field) );
else
return ( flags & ~static_cast<F>(field) );
}
static constexpr uint32_t seconds_per_year = 52 * 7 * 24 * 3600;
static constexpr uint32_t seconds_per_day = 24 * 3600;
static constexpr uint32_t seconds_per_hour = 3600;
static constexpr int64_t useconds_per_year = int64_t(seconds_per_year) * 1000'000ll;
static constexpr int64_t useconds_per_day = int64_t(seconds_per_day) * 1000'000ll;
static constexpr int64_t useconds_per_hour = int64_t(seconds_per_hour) * 1000'000ll;
static constexpr uint32_t blocks_per_day = 2 * seconds_per_day; // half seconds per day
static constexpr int64_t min_activated_stake = 150'000'000'0000;
static constexpr int64_t ram_gift_bytes = 1400;
static constexpr int64_t min_pervote_daily_pay = 100'0000;
static constexpr uint32_t refund_delay_sec = 3 * seconds_per_day;
static constexpr int64_t inflation_precision = 100; // 2 decimals
static constexpr int64_t default_annual_rate = 500; // 5% annual rate
static constexpr int64_t pay_factor_precision = 10000;
static constexpr int64_t default_inflation_pay_factor = 50000; // producers pay share = 10000 / 50000 = 20% of the inflation
static constexpr int64_t default_votepay_factor = 40000; // per-block pay share = 10000 / 40000 = 25% of the producer pay
#ifdef SYSTEM_BLOCKCHAIN_PARAMETERS
struct blockchain_parameters_v1 : eosio::blockchain_parameters
{
eosio::binary_extension<uint32_t> max_action_return_value_size;
EOSLIB_SERIALIZE_DERIVED( blockchain_parameters_v1, eosio::blockchain_parameters,
(max_action_return_value_size) )
};
using blockchain_parameters_t = blockchain_parameters_v1;
#else
using blockchain_parameters_t = eosio::blockchain_parameters;
#endif
/**
* The `eosio.system` smart contract is provided by `block.one` as a sample system contract, and it defines the structures and actions needed for blockchain's core functionality.
*
* Just like in the `eosio.bios` sample contract implementation, there are a few actions which are not implemented at the contract level (`newaccount`, `updateauth`, `deleteauth`, `linkauth`, `unlinkauth`, `canceldelay`, `onerror`, `setabi`, `setcode`), they are just declared in the contract so they will show in the contract's ABI and users will be able to push those actions to the chain via the account holding the `eosio.system` contract, but the implementation is at the EOSIO core level. They are referred to as EOSIO native actions.
*
* - Users can stake tokens for CPU and Network bandwidth, and then vote for producers or
* delegate their vote to a proxy.
* - Producers register in order to be voted for, and can claim per-block and per-vote rewards.
* - Users can buy and sell RAM at a market-determined price.
* - Users can bid on premium names.
* - A resource exchange system (REX) allows token holders to lend their tokens,
* and users to rent CPU and Network resources in return for a market-determined fee.
*/
// A name bid, which consists of:
// - a `newname` name that the bid is for
// - a `high_bidder` account name that is the one with the highest bid so far
// - the `high_bid` which is amount of highest bid
// - and `last_bid_time` which is the time of the highest bid
struct [[eosio::table, eosio::contract("eosio.system")]] name_bid {
name newname;
name high_bidder;
int64_t high_bid = 0; ///< negative high_bid == closed auction waiting to be claimed
time_point last_bid_time;
uint64_t primary_key()const { return newname.value; }
uint64_t by_high_bid()const { return static_cast<uint64_t>(-high_bid); }
};
// A bid refund, which is defined by:
// - the `bidder` account name owning the refund
// - the `amount` to be refunded
struct [[eosio::table, eosio::contract("eosio.system")]] bid_refund {
name bidder;
asset amount;
uint64_t primary_key()const { return bidder.value; }
};
typedef eosio::multi_index< "namebids"_n, name_bid,
indexed_by<"highbid"_n, const_mem_fun<name_bid, uint64_t, &name_bid::by_high_bid> >
> name_bid_table;
typedef eosio::multi_index< "bidrefunds"_n, bid_refund > bid_refund_table;
// Defines new global state parameters.
struct [[eosio::table("global"), eosio::contract("eosio.system")]] eosio_global_state : eosio::blockchain_parameters {
uint64_t free_ram()const { return max_ram_size - total_ram_bytes_reserved; }
uint64_t max_ram_size = 64ll*1024 * 1024 * 1024;
uint64_t total_ram_bytes_reserved = 0;
int64_t total_ram_stake = 0;
block_timestamp last_producer_schedule_update;
time_point last_pervote_bucket_fill;
int64_t pervote_bucket = 0;
int64_t perblock_bucket = 0;
uint32_t total_unpaid_blocks = 0; /// all blocks which have been produced but not paid
int64_t total_activated_stake = 0;
time_point thresh_activated_stake_time;
uint16_t last_producer_schedule_size = 0;
double total_producer_vote_weight = 0; /// the sum of all producer votes
block_timestamp last_name_close;
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE_DERIVED( eosio_global_state, eosio::blockchain_parameters,
(max_ram_size)(total_ram_bytes_reserved)(total_ram_stake)
(last_producer_schedule_update)(last_pervote_bucket_fill)
(pervote_bucket)(perblock_bucket)(total_unpaid_blocks)(total_activated_stake)(thresh_activated_stake_time)
(last_producer_schedule_size)(total_producer_vote_weight)(last_name_close) )
};
// Defines new global state parameters added after version 1.0
struct [[eosio::table("global2"), eosio::contract("eosio.system")]] eosio_global_state2 {
eosio_global_state2(){}
uint16_t new_ram_per_block = 0;
block_timestamp last_ram_increase;
block_timestamp last_block_num; /* deprecated */
double total_producer_votepay_share = 0;
uint8_t revision = 0; ///< used to track version updates in the future.
EOSLIB_SERIALIZE( eosio_global_state2, (new_ram_per_block)(last_ram_increase)(last_block_num)
(total_producer_votepay_share)(revision) )
};
// Defines new global state parameters added after version 1.3.0
struct [[eosio::table("global3"), eosio::contract("eosio.system")]] eosio_global_state3 {
eosio_global_state3() { }
time_point last_vpay_state_update;
double total_vpay_share_change_rate = 0;
EOSLIB_SERIALIZE( eosio_global_state3, (last_vpay_state_update)(total_vpay_share_change_rate) )
};
// Defines new global state parameters to store inflation rate and distribution
struct [[eosio::table("global4"), eosio::contract("eosio.system")]] eosio_global_state4 {
eosio_global_state4() { }
double continuous_rate;
int64_t inflation_pay_factor;
int64_t votepay_factor;
EOSLIB_SERIALIZE( eosio_global_state4, (continuous_rate)(inflation_pay_factor)(votepay_factor) )
};
inline eosio::block_signing_authority convert_to_block_signing_authority( const eosio::public_key& producer_key ) {
return eosio::block_signing_authority_v0{ .threshold = 1, .keys = {{producer_key, 1}} };
}
// Defines `producer_info` structure to be stored in `producer_info` table, added after version 1.0
struct [[eosio::table, eosio::contract("eosio.system")]] producer_info {
name owner;
double total_votes = 0;
eosio::public_key producer_key; /// a packed public key object
bool is_active = true;
std::string url;
uint32_t unpaid_blocks = 0;
time_point last_claim_time;
uint16_t location = 0;
eosio::binary_extension<eosio::block_signing_authority> producer_authority; // added in version 1.9.0
uint64_t primary_key()const { return owner.value; }
double by_votes()const { return is_active ? -total_votes : total_votes; }
bool active()const { return is_active; }
void deactivate() { producer_key = public_key(); producer_authority.reset(); is_active = false; }
eosio::block_signing_authority get_producer_authority()const {
if( producer_authority.has_value() ) {
bool zero_threshold = std::visit( [](auto&& auth ) -> bool {
return (auth.threshold == 0);
}, *producer_authority );
// zero_threshold could be true despite the validation done in regproducer2 because the v1.9.0 eosio.system
// contract has a bug which may have modified the producer table such that the producer_authority field
// contains a default constructed eosio::block_signing_authority (which has a 0 threshold and so is invalid).
if( !zero_threshold ) return *producer_authority;
}
return convert_to_block_signing_authority( producer_key );
}
// The unregprod and claimrewards actions modify unrelated fields of the producers table and under the default
// serialization behavior they would increase the size of the serialized table if the producer_authority field
// was not already present. This is acceptable (though not necessarily desired) because those two actions require
// the authority of the producer who pays for the table rows.
// However, the rmvproducer action and the onblock transaction would also modify the producer table in a similar
// way and increasing its serialized size is not acceptable in that context.
// So, a custom serialization is defined to handle the binary_extension producer_authority
// field in the desired way. (Note: v1.9.0 did not have this custom serialization behavior.)
template<typename DataStream>
friend DataStream& operator << ( DataStream& ds, const producer_info& t ) {
ds << t.owner
<< t.total_votes
<< t.producer_key
<< t.is_active
<< t.url
<< t.unpaid_blocks
<< t.last_claim_time
<< t.location;
if( !t.producer_authority.has_value() ) return ds;
return ds << t.producer_authority;
}
template<typename DataStream>
friend DataStream& operator >> ( DataStream& ds, producer_info& t ) {
return ds >> t.owner
>> t.total_votes
>> t.producer_key
>> t.is_active
>> t.url
>> t.unpaid_blocks
>> t.last_claim_time
>> t.location
>> t.producer_authority;
}
};
// Defines new producer info structure to be stored in new producer info table, added after version 1.3.0
struct [[eosio::table, eosio::contract("eosio.system")]] producer_info2 {
name owner;
double votepay_share = 0;
time_point last_votepay_share_update;
uint64_t primary_key()const { return owner.value; }
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE( producer_info2, (owner)(votepay_share)(last_votepay_share_update) )
};
// Voter info. Voter info stores information about the voter:
// - `owner` the voter
// - `proxy` the proxy set by the voter, if any
// - `producers` the producers approved by this voter if no proxy set
// - `staked` the amount staked
struct [[eosio::table, eosio::contract("eosio.system")]] voter_info {
name owner; /// the voter
name proxy; /// the proxy set by the voter, if any
std::vector<name> producers; /// the producers approved by this voter if no proxy set
int64_t staked = 0;
// Every time a vote is cast we must first "undo" the last vote weight, before casting the
// new vote weight. Vote weight is calculated as:
// stated.amount * 2 ^ ( weeks_since_launch/weeks_per_year)
double last_vote_weight = 0; /// the vote weight cast the last time the vote was updated
// Total vote weight delegated to this voter.
double proxied_vote_weight= 0; /// the total vote weight delegated to this voter as a proxy
bool is_proxy = 0; /// whether the voter is a proxy for others
uint32_t flags1 = 0;
uint32_t reserved2 = 0;
eosio::asset reserved3;
uint64_t primary_key()const { return owner.value; }
enum class flags1_fields : uint32_t {
ram_managed = 1,
net_managed = 2,
cpu_managed = 4
};
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE( voter_info, (owner)(proxy)(producers)(staked)(last_vote_weight)(proxied_vote_weight)(is_proxy)(flags1)(reserved2)(reserved3) )
};
typedef eosio::multi_index< "voters"_n, voter_info > voters_table;
typedef eosio::multi_index< "producers"_n, producer_info,
indexed_by<"prototalvote"_n, const_mem_fun<producer_info, double, &producer_info::by_votes> >
> producers_table;
typedef eosio::multi_index< "producers2"_n, producer_info2 > producers_table2;
typedef eosio::singleton< "global"_n, eosio_global_state > global_state_singleton;
typedef eosio::singleton< "global2"_n, eosio_global_state2 > global_state2_singleton;
typedef eosio::singleton< "global3"_n, eosio_global_state3 > global_state3_singleton;
typedef eosio::singleton< "global4"_n, eosio_global_state4 > global_state4_singleton;
struct [[eosio::table, eosio::contract("eosio.system")]] user_resources {
name owner;
asset net_weight;
asset cpu_weight;
int64_t ram_bytes = 0;
bool is_empty()const { return net_weight.amount == 0 && cpu_weight.amount == 0 && ram_bytes == 0; }
uint64_t primary_key()const { return owner.value; }
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE( user_resources, (owner)(net_weight)(cpu_weight)(ram_bytes) )
};
// Every user 'from' has a scope/table that uses every recipient 'to' as the primary key.
struct [[eosio::table, eosio::contract("eosio.system")]] delegated_bandwidth {
name from;
name to;
asset net_weight;
asset cpu_weight;
bool is_empty()const { return net_weight.amount == 0 && cpu_weight.amount == 0; }
uint64_t primary_key()const { return to.value; }
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE( delegated_bandwidth, (from)(to)(net_weight)(cpu_weight) )
};
struct [[eosio::table, eosio::contract("eosio.system")]] refund_request {
name owner;
time_point_sec request_time;
eosio::asset net_amount;
eosio::asset cpu_amount;
bool is_empty()const { return net_amount.amount == 0 && cpu_amount.amount == 0; }
uint64_t primary_key()const { return owner.value; }
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE( refund_request, (owner)(request_time)(net_amount)(cpu_amount) )
};
typedef eosio::multi_index< "userres"_n, user_resources > user_resources_table;
typedef eosio::multi_index< "delband"_n, delegated_bandwidth > del_bandwidth_table;
typedef eosio::multi_index< "refunds"_n, refund_request > refunds_table;
// `rex_pool` structure underlying the rex pool table. A rex pool table entry is defined by:
// - `version` defaulted to zero,
// - `total_lent` total amount of CORE_SYMBOL in open rex_loans
// - `total_unlent` total amount of CORE_SYMBOL available to be lent (connector),
// - `total_rent` fees received in exchange for lent (connector),
// - `total_lendable` total amount of CORE_SYMBOL that have been lent (total_unlent + total_lent),
// - `total_rex` total number of REX shares allocated to contributors to total_lendable,
// - `namebid_proceeds` the amount of CORE_SYMBOL to be transferred from namebids to REX pool,
// - `loan_num` increments with each new loan
struct [[eosio::table,eosio::contract("eosio.system")]] rex_pool {
uint8_t version = 0;
asset total_lent;
asset total_unlent;
asset total_rent;
asset total_lendable;
asset total_rex;
asset namebid_proceeds;
uint64_t loan_num = 0;
uint64_t primary_key()const { return 0; }
};
typedef eosio::multi_index< "rexpool"_n, rex_pool > rex_pool_table;
// `rex_return_pool` structure underlying the rex return pool table. A rex return pool table entry is defined by:
// - `version` defaulted to zero,
// - `last_dist_time` the last time proceeds from renting, ram fees, and name bids were added to the rex pool,
// - `pending_bucket_time` timestamp of the pending 12-hour return bucket,
// - `oldest_bucket_time` cached timestamp of the oldest 12-hour return bucket,
// - `pending_bucket_proceeds` proceeds in the pending 12-hour return bucket,
// - `current_rate_of_increase` the current rate per dist_interval at which proceeds are added to the rex pool,
// - `proceeds` the maximum amount of proceeds that can be added to the rex pool at any given time
struct [[eosio::table,eosio::contract("eosio.system")]] rex_return_pool {
uint8_t version = 0;
time_point_sec last_dist_time;
time_point_sec pending_bucket_time = time_point_sec::maximum();
time_point_sec oldest_bucket_time = time_point_sec::min();
int64_t pending_bucket_proceeds = 0;
int64_t current_rate_of_increase = 0;
int64_t proceeds = 0;
static constexpr uint32_t total_intervals = 30 * 144; // 30 days
static constexpr uint32_t dist_interval = 10 * 60; // 10 minutes
static constexpr uint8_t hours_per_bucket = 12;
static_assert( total_intervals * dist_interval == 30 * seconds_per_day );
uint64_t primary_key()const { return 0; }
};
typedef eosio::multi_index< "rexretpool"_n, rex_return_pool > rex_return_pool_table;
struct pair_time_point_sec_int64 {
time_point_sec first;
int64_t second;
EOSLIB_SERIALIZE(pair_time_point_sec_int64, (first)(second));
};
// `rex_return_buckets` structure underlying the rex return buckets table. A rex return buckets table is defined by:
// - `version` defaulted to zero,
// - `return_buckets` buckets of proceeds accumulated in 12-hour intervals
struct [[eosio::table,eosio::contract("eosio.system")]] rex_return_buckets {
uint8_t version = 0;
std::vector<pair_time_point_sec_int64> return_buckets; // sorted by first field
uint64_t primary_key()const { return 0; }
};
typedef eosio::multi_index< "retbuckets"_n, rex_return_buckets > rex_return_buckets_table;
// `rex_fund` structure underlying the rex fund table. A rex fund table entry is defined by:
// - `version` defaulted to zero,
// - `owner` the owner of the rex fund,
// - `balance` the balance of the fund.
struct [[eosio::table,eosio::contract("eosio.system")]] rex_fund {
uint8_t version = 0;
name owner;
asset balance;
uint64_t primary_key()const { return owner.value; }
};
typedef eosio::multi_index< "rexfund"_n, rex_fund > rex_fund_table;
// `rex_balance` structure underlying the rex balance table. A rex balance table entry is defined by:
// - `version` defaulted to zero,
// - `owner` the owner of the rex fund,
// - `vote_stake` the amount of CORE_SYMBOL currently included in owner's vote,
// - `rex_balance` the amount of REX owned by owner,
// - `matured_rex` matured REX available for selling
struct [[eosio::table,eosio::contract("eosio.system")]] rex_balance {
uint8_t version = 0;
name owner;
asset vote_stake;
asset rex_balance;
int64_t matured_rex = 0;
std::vector<pair_time_point_sec_int64> rex_maturities; /// REX daily maturity buckets
uint64_t primary_key()const { return owner.value; }
};
typedef eosio::multi_index< "rexbal"_n, rex_balance > rex_balance_table;
// `rex_loan` structure underlying the `rex_cpu_loan_table` and `rex_net_loan_table`. A rex net/cpu loan table entry is defined by:
// - `version` defaulted to zero,
// - `from` account creating and paying for loan,
// - `receiver` account receiving rented resources,
// - `payment` SYS tokens paid for the loan,
// - `balance` is the amount of SYS tokens available to be used for loan auto-renewal,
// - `total_staked` total amount staked,
// - `loan_num` loan number/id,
// - `expiration` the expiration time when loan will be either closed or renewed
// If payment <= balance, the loan is renewed, and closed otherwise.
struct [[eosio::table,eosio::contract("eosio.system")]] rex_loan {
uint8_t version = 0;
name from;
name receiver;
asset payment;
asset balance;
asset total_staked;
uint64_t loan_num;
eosio::time_point expiration;
uint64_t primary_key()const { return loan_num; }
uint64_t by_expr()const { return expiration.elapsed.count(); }
uint64_t by_owner()const { return from.value; }
};
typedef eosio::multi_index< "cpuloan"_n, rex_loan,
indexed_by<"byexpr"_n, const_mem_fun<rex_loan, uint64_t, &rex_loan::by_expr>>,
indexed_by<"byowner"_n, const_mem_fun<rex_loan, uint64_t, &rex_loan::by_owner>>
> rex_cpu_loan_table;
typedef eosio::multi_index< "netloan"_n, rex_loan,
indexed_by<"byexpr"_n, const_mem_fun<rex_loan, uint64_t, &rex_loan::by_expr>>,
indexed_by<"byowner"_n, const_mem_fun<rex_loan, uint64_t, &rex_loan::by_owner>>
> rex_net_loan_table;
struct [[eosio::table,eosio::contract("eosio.system")]] rex_order {
uint8_t version = 0;
name owner;
asset rex_requested;
asset proceeds;
asset stake_change;
eosio::time_point order_time;
bool is_open = true;
void close() { is_open = false; }
uint64_t primary_key()const { return owner.value; }
uint64_t by_time()const { return is_open ? order_time.elapsed.count() : std::numeric_limits<uint64_t>::max(); }
};
typedef eosio::multi_index< "rexqueue"_n, rex_order,
indexed_by<"bytime"_n, const_mem_fun<rex_order, uint64_t, &rex_order::by_time>>> rex_order_table;
struct rex_order_outcome {
bool success;
asset proceeds;
asset stake_change;
};
struct powerup_config_resource {
std::optional<int64_t> current_weight_ratio; // Immediately set weight_ratio to this amount. 1x = 10^15. 0.01x = 10^13.
// Do not specify to preserve the existing setting or use the default;
// this avoids sudden price jumps. For new chains which don't need
// to gradually phase out staking and REX, 0.01x (10^13) is a good
// value for both current_weight_ratio and target_weight_ratio.
std::optional<int64_t> target_weight_ratio; // Linearly shrink weight_ratio to this amount. 1x = 10^15. 0.01x = 10^13.
// Do not specify to preserve the existing setting or use the default.
std::optional<int64_t> assumed_stake_weight; // Assumed stake weight for ratio calculations. Use the sum of total
// staked and total rented by REX at the time the power market
// is first activated. Do not specify to preserve the existing
// setting (no default exists); this avoids sudden price jumps.
// For new chains which don't need to phase out staking and REX,
// 10^12 is probably a good value.
std::optional<time_point_sec> target_timestamp; // Stop automatic weight_ratio shrinkage at this time. Once this
// time hits, weight_ratio will be target_weight_ratio. Ignored
// if current_weight_ratio == target_weight_ratio. Do not specify
// this to preserve the existing setting (no default exists).
std::optional<double> exponent; // Exponent of resource price curve. Must be >= 1. Do not specify
// to preserve the existing setting or use the default.
std::optional<uint32_t> decay_secs; // Number of seconds for the gap between adjusted resource
// utilization and instantaneous resource utilization to shrink
// by 63%. Do not specify to preserve the existing setting or
// use the default.
std::optional<asset> min_price; // Fee needed to reserve the entire resource market weight at the
// minimum price. For example, this could be set to 0.005% of
// total token supply. Do not specify to preserve the existing
// setting or use the default.
std::optional<asset> max_price; // Fee needed to reserve the entire resource market weight at the
// maximum price. For example, this could be set to 10% of total
// token supply. Do not specify to preserve the existing
// setting (no default exists).
EOSLIB_SERIALIZE( powerup_config_resource, (current_weight_ratio)(target_weight_ratio)(assumed_stake_weight)
(target_timestamp)(exponent)(decay_secs)(min_price)(max_price) )
};
struct powerup_config {
powerup_config_resource net; // NET market configuration
powerup_config_resource cpu; // CPU market configuration
std::optional<uint32_t> powerup_days; // `powerup` `days` argument must match this. Do not specify to preserve the
// existing setting or use the default.
std::optional<asset> min_powerup_fee; // Fees below this amount are rejected. Do not specify to preserve the
// existing setting (no default exists).
EOSLIB_SERIALIZE( powerup_config, (net)(cpu)(powerup_days)(min_powerup_fee) )
};
struct powerup_state_resource {
static constexpr double default_exponent = 2.0; // Exponent of 2.0 means that the price to reserve a
// tiny amount of resources increases linearly
// with utilization.
static constexpr uint32_t default_decay_secs = 1 * seconds_per_day; // 1 day; if 100% of bandwidth resources are in a
// single loan, then, assuming no further powerup usage,
// 1 day after it expires the adjusted utilization
// will be at approximately 37% and after 3 days
// the adjusted utilization will be less than 5%.
uint8_t version = 0;
int64_t weight = 0; // resource market weight. calculated; varies over time.
// 1 represents the same amount of resources as 1
// satoshi of SYS staked.
int64_t weight_ratio = 0; // resource market weight ratio:
// assumed_stake_weight / (assumed_stake_weight + weight).
// calculated; varies over time. 1x = 10^15. 0.01x = 10^13.
int64_t assumed_stake_weight = 0; // Assumed stake weight for ratio calculations.
int64_t initial_weight_ratio = powerup_frac; // Initial weight_ratio used for linear shrinkage.
int64_t target_weight_ratio = powerup_frac / 100; // Linearly shrink the weight_ratio to this amount.
time_point_sec initial_timestamp = {}; // When weight_ratio shrinkage started
time_point_sec target_timestamp = {}; // Stop automatic weight_ratio shrinkage at this time. Once this
// time hits, weight_ratio will be target_weight_ratio.
double exponent = default_exponent; // Exponent of resource price curve.
uint32_t decay_secs = default_decay_secs; // Number of seconds for the gap between adjusted resource
// utilization and instantaneous utilization to shrink by 63%.
asset min_price = {}; // Fee needed to reserve the entire resource market weight at
// the minimum price (defaults to 0).
asset max_price = {}; // Fee needed to reserve the entire resource market weight at
// the maximum price.
int64_t utilization = 0; // Instantaneous resource utilization. This is the current
// amount sold. utilization <= weight.
int64_t adjusted_utilization = 0; // Adjusted resource utilization. This is >= utilization and
// <= weight. It grows instantly but decays exponentially.
time_point_sec utilization_timestamp = {}; // When adjusted_utilization was last updated
};
struct [[eosio::table("powup.state"),eosio::contract("eosio.system")]] powerup_state {
static constexpr uint32_t default_powerup_days = 30; // 30 day resource powerup
uint8_t version = 0;
powerup_state_resource net = {}; // NET market state
powerup_state_resource cpu = {}; // CPU market state
uint32_t powerup_days = default_powerup_days; // `powerup` `days` argument must match this.
asset min_powerup_fee = {}; // fees below this amount are rejected
uint64_t primary_key()const { return 0; }
};
typedef eosio::singleton<"powup.state"_n, powerup_state> powerup_state_singleton;
struct [[eosio::table("powup.order"),eosio::contract("eosio.system")]] powerup_order {
uint8_t version = 0;
uint64_t id;
name owner;
int64_t net_weight;
int64_t cpu_weight;
time_point_sec expires;
uint64_t primary_key()const { return id; }
uint64_t by_owner()const { return owner.value; }
uint64_t by_expires()const { return expires.utc_seconds; }
};
typedef eosio::multi_index< "powup.order"_n, powerup_order,
indexed_by<"byowner"_n, const_mem_fun<powerup_order, uint64_t, &powerup_order::by_owner>>,
indexed_by<"byexpires"_n, const_mem_fun<powerup_order, uint64_t, &powerup_order::by_expires>>
> powerup_order_table;
/**
* The `eosio.system` smart contract is provided by `block.one` as a sample system contract, and it defines the structures and actions needed for blockchain's core functionality.
*
* Just like in the `eosio.bios` sample contract implementation, there are a few actions which are not implemented at the contract level (`newaccount`, `updateauth`, `deleteauth`, `linkauth`, `unlinkauth`, `canceldelay`, `onerror`, `setabi`, `setcode`), they are just declared in the contract so they will show in the contract's ABI and users will be able to push those actions to the chain via the account holding the `eosio.system` contract, but the implementation is at the EOSIO core level. They are referred to as EOSIO native actions.
*
* - Users can stake tokens for CPU and Network bandwidth, and then vote for producers or
* delegate their vote to a proxy.
* - Producers register in order to be voted for, and can claim per-block and per-vote rewards.
* - Users can buy and sell RAM at a market-determined price.
* - Users can bid on premium names.
* - A resource exchange system (REX) allows token holders to lend their tokens,
* and users to rent CPU and Network resources in return for a market-determined fee.
* - A resource market separate from REX: `power`.
*/
class [[eosio::contract("eosio.system")]] system_contract : public native {
private:
voters_table _voters;
producers_table _producers;
producers_table2 _producers2;
global_state_singleton _global;
global_state2_singleton _global2;
global_state3_singleton _global3;
global_state4_singleton _global4;
eosio_global_state _gstate;
eosio_global_state2 _gstate2;
eosio_global_state3 _gstate3;
eosio_global_state4 _gstate4;
rammarket _rammarket;
rex_pool_table _rexpool;
rex_return_pool_table _rexretpool;
rex_return_buckets_table _rexretbuckets;
rex_fund_table _rexfunds;
rex_balance_table _rexbalance;
rex_order_table _rexorders;
public:
static constexpr eosio::name active_permission{"active"_n};
static constexpr eosio::name token_account{"eosio.token"_n};
static constexpr eosio::name ram_account{"eosio.ram"_n};
static constexpr eosio::name ramfee_account{"eosio.ramfee"_n};
static constexpr eosio::name stake_account{"eosio.stake"_n};
static constexpr eosio::name bpay_account{"eosio.bpay"_n};
static constexpr eosio::name vpay_account{"eosio.vpay"_n};
static constexpr eosio::name names_account{"eosio.names"_n};
static constexpr eosio::name saving_account{"eosio.saving"_n};
static constexpr eosio::name rex_account{"eosio.rex"_n};
static constexpr eosio::name reserve_account{"eosio.reserv"_n}; // cspell:disable-line
static constexpr eosio::name null_account{"eosio.null"_n};
static constexpr symbol ramcore_symbol = symbol(symbol_code("RAMCORE"), 4);
static constexpr symbol ram_symbol = symbol(symbol_code("RAM"), 0);
static constexpr symbol rex_symbol = symbol(symbol_code("REX"), 4);
system_contract( name s, name code, datastream<const char*> ds );
~system_contract();
// Returns the core symbol by system account name
// @param system_account - the system account to get the core symbol for.
static symbol get_core_symbol( name system_account = "eosio"_n ) {
rammarket rm(system_account, system_account.value);
const static auto sym = get_core_symbol( rm );
return sym;
}
// Actions:
/**
* The Init action initializes the system contract for a version and a symbol.
* Only succeeds when:
* - version is 0 and
* - symbol is found and
* - system token supply is greater than 0,
* - and system contract wasn’t already been initialized.
*
* @param version - the version, has to be 0,
* @param core - the system symbol.
*/
[[eosio::action]]
void init( unsigned_int version, const symbol& core );
/**
* On block action. This special action is triggered when a block is applied by the given producer
* and cannot be generated from any other source. It is used to pay producers and calculate
* missed blocks of other producers. Producer pay is deposited into the producer's stake
* balance and can be withdrawn over time. Once a minute, it may update the active producer config from the
* producer votes. The action also populates the blockinfo table.
*
* @param header - the block header produced.
*/
[[eosio::action]]
void onblock( ignore<block_header> header );
/**
* Set account limits action sets the resource limits of an account
*
* @param account - name of the account whose resource limit to be set,
* @param ram_bytes - ram limit in absolute bytes,
* @param net_weight - fractionally proportionate net limit of available resources based on (weight / total_weight_of_all_accounts),
* @param cpu_weight - fractionally proportionate cpu limit of available resources based on (weight / total_weight_of_all_accounts).
*/
[[eosio::action]]
void setalimits( const name& account, int64_t ram_bytes, int64_t net_weight, int64_t cpu_weight );
/**
* Set account RAM limits action, which sets the RAM limits of an account
*
* @param account - name of the account whose resource limit to be set,
* @param ram_bytes - ram limit in absolute bytes.
*/
[[eosio::action]]
void setacctram( const name& account, const std::optional<int64_t>& ram_bytes );
/**
* Set account NET limits action, which sets the NET limits of an account
*
* @param account - name of the account whose resource limit to be set,
* @param net_weight - fractionally proportionate net limit of available resources based on (weight / total_weight_of_all_accounts).
*/
[[eosio::action]]
void setacctnet( const name& account, const std::optional<int64_t>& net_weight );
/**
* Set account CPU limits action, which sets the CPU limits of an account
*
* @param account - name of the account whose resource limit to be set,
* @param cpu_weight - fractionally proportionate cpu limit of available resources based on (weight / total_weight_of_all_accounts).
*/
[[eosio::action]]
void setacctcpu( const name& account, const std::optional<int64_t>& cpu_weight );
/**
* The activate action, activates a protocol feature
*
* @param feature_digest - hash of the protocol feature to activate.
*/
[[eosio::action]]
void activate( const eosio::checksum256& feature_digest );
// functions defined in delegate_bandwidth.cpp
/**
* Delegate bandwidth and/or cpu action. Stakes SYS from the balance of `from` for the benefit of `receiver`.
*
* @param from - the account to delegate bandwidth from, that is, the account holding
* tokens to be staked,
* @param receiver - the account to delegate bandwidth to, that is, the account to
* whose resources staked tokens are added
* @param stake_net_quantity - tokens staked for NET bandwidth,
* @param stake_cpu_quantity - tokens staked for CPU bandwidth,
* @param transfer - if true, ownership of staked tokens is transferred to `receiver`.
*
* @post All producers `from` account has voted for will have their votes updated immediately.
*/
[[eosio::action]]
void delegatebw( const name& from, const name& receiver,
const asset& stake_net_quantity, const asset& stake_cpu_quantity, bool transfer );
/**
* Setrex action, sets total_rent balance of REX pool to the passed value.
* @param balance - amount to set the REX pool balance.
*/
[[eosio::action]]
void setrex( const asset& balance );
/**
* Deposit to REX fund action. Deposits core tokens to user REX fund.
* All proceeds and expenses related to REX are added to or taken out of this fund.
* An inline transfer from 'owner' liquid balance is executed.
* All REX-related costs and proceeds are deducted from and added to 'owner' REX fund,
* with one exception being buying REX using staked tokens.
* Storage change is billed to 'owner'.
*
* @param owner - REX fund owner account,
* @param amount - amount of tokens to be deposited.
*/
[[eosio::action]]
void deposit( const name& owner, const asset& amount );
/**
* Withdraw from REX fund action, withdraws core tokens from user REX fund.
* An inline token transfer to user balance is executed.
*
* @param owner - REX fund owner account,
* @param amount - amount of tokens to be withdrawn.
*/
[[eosio::action]]
void withdraw( const name& owner, const asset& amount );
/**
* Buyrex action, buys REX in exchange for tokens taken out of user's REX fund by transferring
* core tokens from user REX fund and converts them to REX stake. By buying REX, user is
* lending tokens in order to be rented as CPU or NET resources.
* Storage change is billed to 'from' account.
*
* @param from - owner account name,
* @param amount - amount of tokens taken out of 'from' REX fund.
*
* @pre A voting requirement must be satisfied before action can be executed.
* @pre User must vote for at least 21 producers or delegate vote to proxy before buying REX.
*
* @post User votes are updated following this action.
* @post Tokens used in purchase are added to user's voting power.
* @post Bought REX cannot be sold before 4 days counting from end of day of purchase.
*/
[[eosio::action]]
void buyrex( const name& from, const asset& amount );
/**
* Unstaketorex action, uses staked core tokens to buy REX.
* Storage change is billed to 'owner' account.
*
* @param owner - owner of staked tokens,
* @param receiver - account name that tokens have previously been staked to,
* @param from_net - amount of tokens to be unstaked from NET bandwidth and used for REX purchase,
* @param from_cpu - amount of tokens to be unstaked from CPU bandwidth and used for REX purchase.
*
* @pre A voting requirement must be satisfied before action can be executed.
* @pre User must vote for at least 21 producers or delegate vote to proxy before buying REX.
*
* @post User votes are updated following this action.
* @post Tokens used in purchase are added to user's voting power.
* @post Bought REX cannot be sold before 4 days counting from end of day of purchase.
*/
[[eosio::action]]
void unstaketorex( const name& owner, const name& receiver, const asset& from_net, const asset& from_cpu );
/**
* Sellrex action, sells REX in exchange for core tokens by converting REX stake back into core tokens
* at current exchange rate. If order cannot be processed, it gets queued until there is enough
* in REX pool to fill order, and will be processed within 30 days at most. If successful, user
* votes are updated, that is, proceeds are deducted from user's voting power. In case sell order
* is queued, storage change is billed to 'from' account.
*
* @param from - owner account of REX,
* @param rex - amount of REX to be sold.
*/
[[eosio::action]]
void sellrex( const name& from, const asset& rex );
/**
* Cnclrexorder action, cancels unfilled REX sell order by owner if one exists.
*
* @param owner - owner account name.
*
* @pre Order cannot be cancelled once it's been filled.
*/
[[eosio::action]]
void cnclrexorder( const name& owner );
/**
* Rentcpu action, uses payment to rent as many SYS tokens as possible as determined by market price and
* stake them for CPU for the benefit of receiver, after 30 days the rented core delegation of CPU
* will expire. At expiration, if balance is greater than or equal to `loan_payment`, `loan_payment`
* is taken out of loan balance and used to renew the loan. Otherwise, the loan is closed and user
* is refunded any remaining balance.
* Owner can fund or refund a loan at any time before its expiration.
* All loan expenses and refunds come out of or are added to owner's REX fund.
*
* @param from - account creating and paying for CPU loan, 'from' account can add tokens to loan
* balance using action `fundcpuloan` and withdraw from loan balance using `defcpuloan`
* @param receiver - account receiving rented CPU resources,
* @param loan_payment - tokens paid for the loan, it has to be greater than zero,
* amount of rented resources is calculated from `loan_payment`,
* @param loan_fund - additional tokens can be zero, and is added to loan balance.
* Loan balance represents a reserve that is used at expiration for automatic loan renewal.
*/
[[eosio::action]]
void rentcpu( const name& from, const name& receiver, const asset& loan_payment, const asset& loan_fund );
/**
* Rentnet action, uses payment to rent as many SYS tokens as possible as determined by market price and
* stake them for NET for the benefit of receiver, after 30 days the rented core delegation of NET
* will expire. At expiration, if balance is greater than or equal to `loan_payment`, `loan_payment`
* is taken out of loan balance and used to renew the loan. Otherwise, the loan is closed and user
* is refunded any remaining balance.
* Owner can fund or refund a loan at any time before its expiration.
* All loan expenses and refunds come out of or are added to owner's REX fund.
*
* @param from - account creating and paying for NET loan, 'from' account can add tokens to loan
* balance using action `fundnetloan` and withdraw from loan balance using `defnetloan`,
* @param receiver - account receiving rented NET resources,
* @param loan_payment - tokens paid for the loan, it has to be greater than zero,
* amount of rented resources is calculated from `loan_payment`,
* @param loan_fund - additional tokens can be zero, and is added to loan balance.
* Loan balance represents a reserve that is used at expiration for automatic loan renewal.
*/
[[eosio::action]]
void rentnet( const name& from, const name& receiver, const asset& loan_payment, const asset& loan_fund );
/**
* Fundcpuloan action, transfers tokens from REX fund to the fund of a specific CPU loan in order to
* be used for loan renewal at expiry.
*
* @param from - loan creator account,
* @param loan_num - loan id,
* @param payment - tokens transferred from REX fund to loan fund.
*/
[[eosio::action]]
void fundcpuloan( const name& from, uint64_t loan_num, const asset& payment );
/**
* Fundnetloan action, transfers tokens from REX fund to the fund of a specific NET loan in order to
* be used for loan renewal at expiry.
*
* @param from - loan creator account,
* @param loan_num - loan id,
* @param payment - tokens transferred from REX fund to loan fund.
*/
[[eosio::action]]
void fundnetloan( const name& from, uint64_t loan_num, const asset& payment );
/**
* Defcpuloan action, withdraws tokens from the fund of a specific CPU loan and adds them to REX fund.
*
* @param from - loan creator account,
* @param loan_num - loan id,
* @param amount - tokens transferred from CPU loan fund to REX fund.
*/
[[eosio::action]]
void defcpuloan( const name& from, uint64_t loan_num, const asset& amount );
/**
* Defnetloan action, withdraws tokens from the fund of a specific NET loan and adds them to REX fund.
*
* @param from - loan creator account,
* @param loan_num - loan id,
* @param amount - tokens transferred from NET loan fund to REX fund.
*/
[[eosio::action]]
void defnetloan( const name& from, uint64_t loan_num, const asset& amount );
/**
* Updaterex action, updates REX owner vote weight to current value of held REX tokens.
*
* @param owner - REX owner account.
*/