-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
executable file
·1647 lines (1449 loc) · 70.7 KB
/
lib.rs
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
/*
ABOUT THIS CONTRACT...
This contract allows users to post public broadcast messages to the Geode Blockchain.
In this contract, to endorse a message is to upvote it (a kind of like button that might
boost it's visibility in the front end). This contract also allows users to:
- follow and unfollow specific accounts,
- reply to regular message posts (NOT paid message posts),
- declare their interests,
- see paid messages that fit their interests, and
- be paid in GEODE to endorse or upvote a paid message.
*/
#![cfg_attr(not(feature = "std"), no_std, no_main)]
#[ink::contract]
mod geode_social {
use ink::prelude::vec::Vec;
use ink::prelude::vec;
use ink::prelude::string::String;
use ink::storage::Mapping;
use ink::env::hash::{Sha2x256, HashOutput};
// PRELIMINARY STORAGE STRUCTURES >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#[derive(Clone, Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct Settings {
username: Vec<u8>,
interests: Vec<u8>,
max_feed: u128,
max_paid_feed: u128,
last_update: u64
}
impl Default for Settings {
fn default() -> Settings {
Settings {
username: <Vec<u8>>::default(),
interests: <Vec<u8>>::default(),
max_feed: 1000,
max_paid_feed: 1000,
last_update: u64::default()
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct Following {
following: Vec<AccountId>,
}
impl Default for Following {
fn default() -> Following {
Following {
following: <Vec<AccountId>>::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct Blocked {
blocked: Vec<AccountId>,
}
impl Default for Blocked {
fn default() -> Blocked {
Blocked {
blocked: <Vec<AccountId>>::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Default)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct Messages {
messages: Vec<Hash>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct PaidMessageDetails {
message_id: Hash,
from_acct: AccountId,
username: Vec<u8>,
message: Vec<u8>,
link: Vec<u8>,
link2: Vec<u8>,
endorser_count: u128,
timestamp: u64,
paid_endorser_max: u128,
endorser_payment: Balance,
target_interests: Vec<u8>,
total_staked: Balance,
endorsers: Vec<AccountId>,
staked_balance: Balance,
}
impl Default for PaidMessageDetails {
fn default() -> PaidMessageDetails {
PaidMessageDetails {
message_id: Hash::default(),
from_acct: AccountId::from([0x0; 32]),
username: <Vec<u8>>::default(),
message: <Vec<u8>>::default(),
link: <Vec<u8>>::default(),
link2: <Vec<u8>>::default(),
endorser_count: 0,
timestamp: u64::default(),
paid_endorser_max: u128::default(),
endorser_payment: Balance::default(),
target_interests: <Vec<u8>>::default(),
total_staked: Balance::default(),
endorsers: <Vec<AccountId>>::default(),
staked_balance: Balance::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct MessageDetails {
message_id: Hash,
reply_to: Hash,
from_acct: AccountId,
username: Vec<u8>,
message: Vec<u8>,
link: Vec<u8>,
link2: Vec<u8>,
endorser_count: u128,
reply_count: u128,
timestamp: u64,
}
impl Default for MessageDetails {
fn default() -> MessageDetails {
MessageDetails {
message_id: Hash::default(),
reply_to: Hash::default(),
from_acct: AccountId::from([0x0; 32]),
username: <Vec<u8>>::default(),
message: <Vec<u8>>::default(),
link: <Vec<u8>>::default(),
link2: <Vec<u8>>::default(),
endorser_count: 0,
reply_count: 0,
timestamp: u64::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct MyFeed {
maxfeed: u128,
blocked: Vec<AccountId>,
myfeed: Vec<MessageDetails>,
}
impl Default for MyFeed {
fn default() -> MyFeed {
MyFeed {
maxfeed: 1000,
blocked: <Vec<AccountId>>::default(),
myfeed: <Vec<MessageDetails>>::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct MyPaidFeed {
maxfeed: u128,
myinterests: Vec<u8>,
blocked: Vec<AccountId>,
mypaidfeed: Vec<PaidMessageDetails>,
}
impl Default for MyPaidFeed {
fn default() -> MyPaidFeed {
MyPaidFeed {
maxfeed: 1000,
myinterests: <Vec<u8>>::default(),
blocked: <Vec<AccountId>>::default(),
mypaidfeed: <Vec<PaidMessageDetails>>::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct SocialProfile {
searched_account: AccountId,
username: Vec<u8>,
followers: u128,
following: Vec<AccountId>,
message_list: Vec<MessageDetails>,
}
impl Default for SocialProfile {
fn default() -> SocialProfile {
SocialProfile {
searched_account: AccountId::from([0x0; 32]),
username: <Vec<u8>>::default(),
followers: 0,
following: <Vec<AccountId>>::default(),
message_list: <Vec<MessageDetails>>::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std",derive(ink::storage::traits::StorageLayout,))]
pub struct RewardSettings {
reward_on: u8,
reward_root_set: u8,
reward_root: AccountId,
reward_interval: u128,
reward_amount: Balance,
reward_balance: Balance,
reward_payouts: Balance,
claim_counter: u128,
}
impl Default for RewardSettings {
fn default() -> RewardSettings {
RewardSettings {
reward_on: u8::default(),
reward_root_set: u8::default(),
reward_root: AccountId::from([0x0; 32]),
reward_interval: u128::default(),
reward_amount: Balance::default(),
reward_balance: Balance::default(),
reward_payouts: Balance::default(),
claim_counter: u128::default(),
}
}
}
// EVENT DEFINITIONS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#[ink(event)]
// Writes a broadcast message to the blockchain
pub struct MessageBroadcast {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
message: Vec<u8>,
#[ink(topic)]
message_id: Hash,
link: Vec<u8>,
link2: Vec<u8>,
reply_to: Hash,
timestamp: u64
}
#[ink(event)]
// Writes a paid broadcast message to the blockchain
pub struct PaidMessageBroadcast {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
message: Vec<u8>,
#[ink(topic)]
message_id: Hash,
link: Vec<u8>,
link2: Vec<u8>,
timestamp: u64,
paid_endorser_max: u128,
endorser_payment: Balance,
target_interests: Vec<u8>,
total_staked: Balance
}
#[ink(event)]
// Writes the new endorsement to the blockchain
pub struct MessageElevated {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
message_id: Hash,
#[ink(topic)]
endorser: AccountId
}
#[ink(event)]
// Writes the new paid endorsement to the blockchain
pub struct PaidMessageElevated {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
message_id: Hash,
#[ink(topic)]
endorser: AccountId
}
#[ink(event)]
// Writes the new follow to the blockchain
pub struct NewFollow {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
is_following: AccountId,
}
#[ink(event)]
// Writes the new UNfollow to the blockchain
pub struct NewUnFollow {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
stopped_following: AccountId,
}
#[ink(event)]
// Writes the new BLOCK to the blockchain
pub struct NewBlock {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
blocked: AccountId,
}
#[ink(event)]
// Writes the new unBLOCK to the blockchain
pub struct NewUnBlock {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
unblocked: AccountId,
}
#[ink(event)]
// Writes the new settings update to the blockchain
pub struct SettingsUpdated {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
username: Vec<u8>,
#[ink(topic)]
interests: Vec<u8>,
}
#[ink(event)]
// Writes the new reward to the blockchain
pub struct AccountRewardedSocial {
#[ink(topic)]
claimant: AccountId,
reward: Balance,
}
// ERROR DEFINITIONS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#[derive(Debug, PartialEq, Eq)]
#[ink::scale_derive(Encode, Decode, TypeInfo)]
pub enum Error {
// Following an account that you follow already
CannotFollow,
// Unfollowing an account that you don't follow anyway
NotFollowing,
NotInFollowerList,
// Blocking an account that you already blocked
CannotBlock,
// Unblocking an account that you never blocked
NotBlocked,
// Elevating a message that does not exist
NonexistentMessage,
// Elevating a paid message that does not exist
NonexistentPaidMessage,
// Elevating the same message twice
DuplicateEndorsement,
// trying to update your interest before 24 hours have past
CannotUpdateInterestsWithin24Hours,
// Too many interests in your list
InterestsTooLong,
// Trying to endorse a paid message outside your interests
NoInterestMatch,
// When a paid message has run out of available endorsements
NoMorePaidEndorsementsAvailable,
// if the contract has no money to pay
ZeroBalance,
// if the endorser payment fails
EndorserPayoutFailed,
// Reentrancy Guard error
UsernameTaken,
// if you are replying to a message that does not exist
ReplyingToMessageDoesNotExist,
// too much data in the inputs
DataTooLarge,
// paid message bid is too low to get into the set
BidTooLow,
// replies are full, cannot reply to this post
RepliesFull,
// Caller doee not have permission
PermissionDenied,
// reward account payout failed
PayoutFailed,
}
// ACTUAL CONTRACT STORAGE STRUCT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#[ink(storage)]
pub struct ContractStorage {
account_settings_map: Mapping<AccountId, Settings>,
account_following_map: Mapping<AccountId, Following>,
account_followers_map: Mapping<AccountId, u128>,
account_blocked_map: Mapping<AccountId, Blocked>,
account_messages_map: Mapping<AccountId, Messages>,
account_paid_messages_map: Mapping<AccountId, Messages>,
account_elevated_map: Mapping<AccountId, Hash>,
message_map: Mapping<Hash, MessageDetails>,
reply_map: Mapping<Hash, MessageDetails>,
paid_message_map: Mapping<Hash, PaidMessageDetails>,
target_interests_map: Mapping<Vec<u8>, Messages>,
message_reply_map: Mapping<Hash, Messages>,
username_map: Mapping<Vec<u8>, AccountId>,
reward_root_set: u8,
reward_root: AccountId,
reward_interval: u128,
reward_amount: Balance,
reward_on: u8,
reward_balance: Balance,
reward_payouts: Balance,
claim_counter: u128,
}
// BEGIN CONTRACT LOGIC >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
impl ContractStorage {
// CONSTRUCTORS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Constructors are implicitly payable.
#[ink(constructor)]
pub fn new() -> Self {
Self {
account_settings_map: Mapping::default(),
account_following_map: Mapping::default(),
account_followers_map: Mapping::default(),
account_blocked_map: Mapping::default(),
account_messages_map: Mapping::default(),
account_paid_messages_map: Mapping::default(),
account_elevated_map: Mapping::default(),
message_map: Mapping::default(),
reply_map: Mapping::default(),
paid_message_map: Mapping::default(),
target_interests_map: Mapping::default(),
message_reply_map: Mapping::default(),
username_map: Mapping::default(),
reward_root_set: 0,
reward_root: AccountId::from([0x0; 32]),
reward_interval: 1000000,
reward_amount: 0,
reward_on: 0,
reward_balance: 0,
reward_payouts: 0,
claim_counter: 0,
}
}
// MESSAGE FUNCTIONS THAT CHANGE DATA IN THE CONTRACT STORAGE >>>>>>>>>>>>>>>>>>>
// 🟢 0 SEND MESSAGE PUBLIC (TOP LEVEL MESSAGE, NOT A REPLY)
// sends a broadcast public message on the chain
#[ink(message)]
pub fn send_message_public (&mut self,
new_message: Vec<u8>,
photo_or_youtube_link: Vec<u8>,
website_or_document_link: Vec<u8>,
) -> Result<(), Error> {
// check data limits on all inputs:
// message 300 characters (600 length), links 300 characters (600 length)
if new_message.len() > 600 || photo_or_youtube_link.len() > 600
|| website_or_document_link.len() > 600 {
// error - data too large
return Err(Error::DataTooLarge);
}
let new_message_clone = new_message.clone();
let new_message_clone2 = new_message.clone();
let link_clone = photo_or_youtube_link.clone();
let link2_clone = website_or_document_link.clone();
// set up the data that will go into the new_message_id
let from = Self::env().caller();
let new_timestamp = self.env().block_timestamp();
// create the new_message_id by hashing the above data
let encodable = (from, new_message, new_timestamp); // Implements `scale::Encode`
let mut new_message_id_u8 = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buffer
ink::env::hash_encoded::<Sha2x256, _>(&encodable, &mut new_message_id_u8);
let new_message_id: Hash = Hash::from(new_message_id_u8);
// SET UP THE MESSAGE DETAILS FOR THE NEW MESSAGE
let caller = Self::env().caller();
let fromusername = self.account_settings_map.get(caller).unwrap_or_default().username;
let new_details = MessageDetails {
message_id: new_message_id,
reply_to: Hash::default(),
from_acct: Self::env().caller(),
username: fromusername,
message: new_message_clone,
link: photo_or_youtube_link,
link2: website_or_document_link,
endorser_count: 0,
reply_count: 0,
timestamp: self.env().block_timestamp(),
};
// UPDATE MESSAGE MAP AND VECTOR
// add the message id and its details to the message_map
if self.message_map.try_insert(&new_message_id, &new_details).is_err() {
return Err(Error::DataTooLarge);
}
// UPDATE ACCOUNT MESSAGES MAP
// get the messages vector for this account
let caller = Self::env().caller();
let mut current_messages = self.account_messages_map.get(&caller).unwrap_or_default();
// Keep only the 3 most recent message hashes
if current_messages.messages.len() > 2 {
// get the id for the oldest message
let oldest = current_messages.messages[0];
// remove the oldest from the message_map
self.message_map.remove(oldest);
// remove the oldest message from account_messages_map
current_messages.messages.remove(0);
// remove all the replies to the oldest message from the reply_map
let replies = self.message_reply_map.get(oldest).unwrap_or_default();
for id in replies.messages.iter() {
self.reply_map.remove(id);
}
// remove the oldest message from the message_reply_map
self.message_reply_map.remove(oldest);
}
// add the new message to the end of the storage
current_messages.messages.push(new_message_id);
// update the account_messages_map
self.account_messages_map.insert(&caller, ¤t_messages);
// EMIT EVENT to register the post to the chain
Self::env().emit_event(MessageBroadcast {
from: Self::env().caller(),
message: new_message_clone2,
message_id: new_message_id,
link: link_clone,
link2: link2_clone,
reply_to: Hash::default(),
timestamp: self.env().block_timestamp()
});
// REWARD PROGRAM ACTIONS... update the claim_counter
self.claim_counter = self.claim_counter.wrapping_add(1);
// IF conditions are met THEN payout a reward
let min = self.reward_amount.saturating_add(10);
let payout: Balance = self.reward_amount;
if self.reward_on == 1 && self.reward_balance > payout && self.env().balance() > min
&& self.claim_counter.checked_rem_euclid(self.reward_interval) == Some(0) {
// payout
if self.env().transfer(caller, payout).is_err() {
return Err(Error::PayoutFailed);
}
// update reward_balance
self.reward_balance = self.reward_balance.saturating_sub(payout);
// update reward_payouts
self.reward_payouts = self.reward_payouts.saturating_add(payout);
// emit an event to register the reward to the chain
Self::env().emit_event(AccountRewardedSocial {
claimant: caller,
reward: payout
});
}
// END REWARD PROGRAM ACTIONS
Ok(())
}
// 🟢 1 SEND PAID MESSAGE PUBLIC
// sends a paid public broadcast message post
// and offers coin to the first X accounts to endorse/elevate the post
#[ink(message, payable)]
pub fn send_paid_message_public (&mut self,
new_message: Vec<u8>,
photo_or_youtube_link: Vec<u8>,
website_or_document_link: Vec<u8>,
maximum_number_of_paid_endorsers: u128,
payment_per_endorser: Balance,
target_interests: Vec<u8>
) -> Result<(), Error> {
// check that the inputs are not too long
// message 300 characters (600 length), links: 300 characters (600 length)
// target interests 50 characters (100 length)
if photo_or_youtube_link.len() > 600 || target_interests.len() > 100
|| target_interests.len() > 600 || website_or_document_link.len() > 600 {
// error - data too large
return Err(Error::DataTooLarge);
}
let caller = Self::env().caller();
let new_message_clone = new_message.clone();
let new_message_clone2 = new_message.clone();
let interests_clone = target_interests.clone();
let interests_clone2 = target_interests.clone();
let link_clone = photo_or_youtube_link.clone();
let link2_clone = website_or_document_link.clone();
// CREATE THE MESSAGE ID HASH
// set up the data that will go into the new_message_id
let from = Self::env().caller();
let new_timestamp = self.env().block_timestamp();
// create the new_message_id by hashing the above data
let encodable = (from, new_message, new_timestamp); // Implements `scale::Encode`
let mut new_message_id_u8 = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buffer
ink::env::hash_encoded::<Sha2x256, _>(&encodable, &mut new_message_id_u8);
let new_message_id: Hash = Hash::from(new_message_id_u8);
// COLLECT PAYMENT FROM THE CALLER
// the 'payable' tag on this message allows the user to send any amount
// so we determine here what that will give each endorser
let staked: Balance = self.env().transferred_value();
// MAKE THE PAID MESSAGE DETAILS STRUCT
let fromusername = self.account_settings_map.get(caller).unwrap_or_default().username;
// set up the paid message details
let new_details = PaidMessageDetails {
message_id: new_message_id,
from_acct: Self::env().caller(),
username: fromusername,
message: new_message_clone,
link: photo_or_youtube_link,
link2: website_or_document_link,
endorser_count: 0,
timestamp: self.env().block_timestamp(),
paid_endorser_max: maximum_number_of_paid_endorsers,
endorser_payment: payment_per_endorser,
target_interests: target_interests,
total_staked: staked,
endorsers: vec![Self::env().caller()],
staked_balance: staked,
};
// if the account paid messages are full, kick out the oldest from everywhere
// get the messages vector for this account
let mut current_messages = self.account_paid_messages_map.get(&caller).unwrap_or_default();
// if the paid messages vector is full, remove the oldest message
if current_messages.messages.len() > 54 {
// get the id hash and interests for the oldest message
let oldest = current_messages.messages[0];
let old_interests = self.paid_message_map.get(oldest).unwrap_or_default().target_interests;
let old_interests_clone = old_interests.clone();
// remove the oldest from the paid_message_map
self.paid_message_map.remove(oldest);
// remove the oldest from the target_interests_map
let mut old_interests_vec = self.target_interests_map.get(old_interests).unwrap_or_default();
old_interests_vec.messages.retain(|value| *value != oldest);
self.target_interests_map.insert(old_interests_clone, &old_interests_vec);
// remove the oldest from the account_paid_messages_map
current_messages.messages.remove(0);
}
// IF THERE ARE TOO MANY MESSAGES FOR THIS INTERESTS TARGET, THROW OUT THE LOW BIDDER
// get the current set of messages that match this target
let mut matching_messages = self.target_interests_map.get(&interests_clone).unwrap_or_default();
// if there are > 55 messages for this target, remove the lowest bidder
if matching_messages.messages.len() > 54 {
// determine if this message bids high enough...
// check the other bids and find the lowest
let first_hash = matching_messages.messages[0];
let mut low_bid: Balance = self.paid_message_map.get(first_hash).unwrap_or_default().endorser_payment;
let mut low_index: usize = 0;
for (i, ad) in matching_messages.messages.iter().enumerate() {
// get the bid and index
let bid: Balance = self.paid_message_map.get(ad).unwrap_or_default().endorser_payment;
if bid < low_bid {
low_bid = bid;
low_index = i;
}
}
if payment_per_endorser > low_bid {
// kick out the low bidder
matching_messages.messages.remove(low_index);
// we do not remove the low bidder out of the account_paid_messages_map
// or the paid_message_map becuase they will need to be able to get
// their money back by endorsing their own message.
}
else {
// error bid not high enough
return Err(Error::BidTooLow);
}
}
// add the message id and its details to the paid message_map
if self.paid_message_map.try_insert(&new_message_id, &new_details).is_err() {
return Err(Error::DataTooLarge);
}
// add this message to the messages vector for this account
current_messages.messages.push(new_message_id);
// update the account_messages_map
self.account_paid_messages_map.insert(&caller, ¤t_messages);
// add the new message to the list for these target interests
matching_messages.messages.push(new_message_id);
// update the mapping
self.target_interests_map.insert(&interests_clone, &matching_messages);
// EMIT AN EVENT (to register the post to the chain)
Self::env().emit_event(PaidMessageBroadcast {
from: Self::env().caller(),
message: new_message_clone2,
message_id: new_message_id,
link: link_clone,
link2: link2_clone,
timestamp: self.env().block_timestamp(),
paid_endorser_max: maximum_number_of_paid_endorsers,
endorser_payment: payment_per_endorser,
target_interests: interests_clone2,
total_staked: staked
});
// REWARD PROGRAM ACTIONS... update the claim_counter
self.claim_counter = self.claim_counter.wrapping_add(1);
// IF conditions are met THEN payout a reward
let min = self.reward_amount.saturating_add(10);
let payout: Balance = self.reward_amount;
if self.reward_on == 1 && self.reward_balance > payout && self.env().balance() > min
&& self.claim_counter.checked_rem_euclid(self.reward_interval) == Some(0) {
// payout
if self.env().transfer(caller, payout).is_err() {
return Err(Error::PayoutFailed);
}
// update reward_balance
self.reward_balance = self.reward_balance.saturating_sub(payout);
// update reward_payouts
self.reward_payouts = self.reward_payouts.saturating_add(payout);
// emit an event to register the reward to the chain
Self::env().emit_event(AccountRewardedSocial {
claimant: caller,
reward: payout
});
}
// END REWARD PROGRAM ACTIONS
Ok(())
}
// 🟢 2 ELEVATE MESSAGE
// upvotes a public message by endorsing it on chain (unpaid)
#[ink(message)]
pub fn elevate_message(&mut self, this_message_id: Hash) -> Result<(), Error> {
// Does the message_id exist in the message_map? ...
if self.message_map.contains(&this_message_id) {
// Get the contract caller's Account ID
let caller = Self::env().caller();
// Get the details for this message_id from the message_map
let current_details = self.message_map.get(&this_message_id).unwrap_or_default();
// Is it your own message?...
if current_details.from_acct == caller {
// If TRUE, return an Error... DuplicateEndorsement
return Err(Error::DuplicateEndorsement)
}
else {
// update the endorser count
let new_endorser_count = current_details.endorser_count.saturating_add(1);
// Update the details in storage for this message
let updated_details: MessageDetails = MessageDetails {
message_id: current_details.message_id,
reply_to: current_details.reply_to,
from_acct: current_details.from_acct,
username: current_details.username,
message: current_details.message,
link: current_details.link,
link2: current_details.link2,
endorser_count: new_endorser_count,
reply_count: current_details.reply_count,
timestamp: current_details.timestamp,
};
// Update the message_map
if self.message_map.try_insert(&this_message_id, &updated_details).is_err() {
return Err(Error::DataTooLarge);
}
// Add this message to the account_elevated_map for this caller
self.account_elevated_map.insert(&caller, &this_message_id);
// Emit an event to register the endorsement to the chain...
Self::env().emit_event(MessageElevated {
from: updated_details.from_acct,
message_id: this_message_id,
endorser: Self::env().caller()
});
Ok(())
}
}
else {
// if the message_id does not exist ...Error: Nonexistent Message
return Err(Error::NonexistentMessage);
}
}
// 🟢 3 ELEVATE PAID MESSAGE
// endorses a paid message and pays the endorser accordingly
#[ink(message)]
pub fn elevate_paid_message(&mut self, this_message_id: Hash) -> Result<(), Error> {
// Does the message_id exist in the paid_message_map? If TRUE then...
if self.paid_message_map.contains(&this_message_id) {
// Get the contract caller's Account ID
let caller = Self::env().caller();
// Get the details for this paid message...
let mut current_details = self.paid_message_map.get(&this_message_id).unwrap_or_default();
// Is the caller already in the endorsers list for this message?
if current_details.endorsers.contains(&caller) {
// If TRUE, return an Error... DuplicateEndorsement
return Err(Error::DuplicateEndorsement)
}
else {
// If the caller is NOT already an endorser...
// Does the caller match the interests required for payment?
// Get the callers list of interests...
let caller_interests = self.account_settings_map.get(&caller).unwrap_or_default().interests;
// check to see if the caller's interests include the target_interests
let caller_interests_string = String::from_utf8(caller_interests).unwrap_or_default();
let targetvecu8 = current_details.target_interests.clone();
let target_string = String::from_utf8(targetvecu8).unwrap_or_default();
if caller_interests_string.contains(&target_string) {
// Has this paid message hit its limit on paid endorsements?
let max_endorsements = current_details.paid_endorser_max;
let current_endorsement_number: u128 = current_details.endorser_count;
if current_endorsement_number < max_endorsements {
// Pay the endorser the right amount from the contract
let mut paythis: Balance = current_details.endorser_payment;
// if the endorser is the advertiser, refund the remainder in full
if caller == current_details.from_acct {
paythis = current_details.staked_balance;
}
let contractmin: Balance = paythis.saturating_add(11);
// Check that there is a nonzero balance on the contract > existential deposit
// plus the payout plus one
if self.env().balance() > contractmin && current_details.staked_balance >= paythis {
// pay the endorser the amount paythis
if self.env().transfer(caller, paythis).is_err() {
return Err(Error::EndorserPayoutFailed);
}
}
// if the balance is zero, Error (ZeroBalance)
else {
return Err(Error::ZeroBalance);
}
// update the endorsers vector...
// if there are already 400 endorsers, kick out the oldest endorser
if current_details.endorsers.len() > 399 {
current_details.endorsers.remove(0);
}
// Add this endorser to the vector of endorsing accounts
current_details.endorsers.push(caller);
// update the endorser count
let new_endorser_count = current_details.endorser_count.saturating_add(1);
// update the staked balance
let new_balance: Balance = current_details.staked_balance.saturating_sub(paythis);
// Update the details in storage for this paid message
let updated_details: PaidMessageDetails = PaidMessageDetails {
message_id: current_details.message_id,
from_acct: current_details.from_acct,
username: current_details.username,
message: current_details.message,
link: current_details.link,
link2: current_details.link2,
endorser_count: new_endorser_count,
timestamp: current_details.timestamp,
paid_endorser_max: current_details.paid_endorser_max,
endorser_payment: current_details.endorser_payment,
target_interests: current_details.target_interests,
total_staked: current_details.total_staked,
endorsers: current_details.endorsers,
staked_balance: new_balance,
};
// Update the paid_message_map
if self.paid_message_map.try_insert(&this_message_id, &updated_details).is_err() {
return Err(Error::DataTooLarge);
}
// Emit an event to register the endorsement to the chain
// but only if the caller is not the advertiser
if caller != updated_details.from_acct {
Self::env().emit_event(PaidMessageElevated {
from: updated_details.from_acct,
message_id: this_message_id,
endorser: Self::env().caller()
});
}
}
else {
// return an error that there are no endorsements available
return Err(Error::NoMorePaidEndorsementsAvailable)
}
}
else {
return Err(Error::NoInterestMatch);
}
Ok(())
}
}
else {
// if the message_id does not exist ...Error: Nonexistent Paid Message
return Err(Error::NonexistentPaidMessage);
}
}
// 🟢 4 FOLLOW ACCOUNT
// allows a user to follow another accountId's messages
#[ink(message)]
pub fn follow_account (&mut self, follow: AccountId
) -> Result<(), Error> {
let caller = Self::env().caller();
// Is this account already being followed? or is the caller trying to follow themselves?
let mut current_follows = self.account_following_map.get(&caller).unwrap_or_default();
if current_follows.following.contains(&follow) || caller == follow {
return Err(Error::CannotFollow);
}
// Otherwise, update the account_following_map for this caller
else {
// if there are already > 98 accounts in the follow list, keep the most recent 99
if current_follows.following.len() > 98 {
// kick out the oldest follow
current_follows.following.remove(0);
}
// add the new follow to the the vector of accounts caller is following
current_follows.following.push(follow);
// Update (overwrite) the account_following_map entry in the storage
self.account_following_map.insert(&caller, ¤t_follows);
// get the number of current followers for the followed account
let mut current_followers = self.account_followers_map.get(&follow).unwrap_or_default();
// add the caller to the count of followers for this account
current_followers = current_followers.saturating_add(1);
// Update (overwrite) the account_followers_map entry in the storage
self.account_followers_map.insert(&follow, ¤t_followers);
// Emit an event to register the follow to the chain
// but only if the caller is not the follow
if caller != follow {
Self::env().emit_event(NewFollow {
from: caller,
is_following: follow,
});
}
}
Ok(())
}