-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
group.js
1832 lines (1698 loc) · 85.6 KB
/
group.js
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
/* globals fetchServerTime */
'use strict'
import { Errors, L } from '@common/common.js'
import sbp from '@sbp/sbp'
import { DELETED_CHATROOM, JOINED_GROUP, LEFT_CHATROOM } from '@utils/events.js'
import { actionRequireInnerSignature, arrayOf, boolean, number, numberRange, object, objectMaybeOf, objectOf, optional, string, stringMax, tupleOf, validatorFrom, unionOf } from '~/frontend/model/contracts/misc/flowTyper.js'
import { ChelErrorGenerator } from '~/shared/domains/chelonia/errors.js'
import { findForeignKeysByContractID, findKeyIdByName } from '~/shared/domains/chelonia/utils.js'
import {
MAX_HASH_LEN,
MAX_MEMO_LEN,
CHATROOM_GENERAL_NAME, CHATROOM_PRIVACY_LEVEL, CHATROOM_TYPES,
GROUP_CURRENCY_MAX_CHAR,
GROUP_PAYMENT_METHOD_MAX_CHAR,
GROUP_DESCRIPTION_MAX_CHAR,
GROUP_NAME_MAX_CHAR,
GROUP_MAX_PLEDGE_AMOUNT,
GROUP_NON_MONETARY_CONTRIBUTION_MAX_CHAR,
GROUP_MINCOME_MAX,
GROUP_DISTRIBUTION_PERIOD_MAX_DAYS,
CHATROOM_NAME_LIMITS_IN_CHARS,
CHATROOM_DESCRIPTION_LIMITS_IN_CHARS,
INVITE_EXPIRES_IN_DAYS,
MAX_ARCHIVED_PERIODS,
MAX_ARCHIVED_PROPOSALS,
MAX_SAVED_PERIODS,
PAYMENTS_ARCHIVED,
PROFILE_STATUS,
PROPOSAL_ARCHIVED,
PROPOSAL_GENERIC,
PROPOSAL_GROUP_SETTING_CHANGE,
PROPOSAL_INVITE_MEMBER,
PROPOSAL_PROPOSAL_SETTING_CHANGE,
PROPOSAL_REMOVE_MEMBER,
STATUS_CANCELLED, STATUS_EXPIRED, STATUS_OPEN
} from './shared/constants.js'
import { adjustedDistribution, unadjustedDistribution } from './shared/distribution/distribution.js'
import { paymentHashesFromPaymentPeriod, referenceTally } from './shared/functions.js'
import groupGetters from './shared/getters/group.js'
import { cloneDeep, deepEqualJSONType, merge, omit } from './shared/giLodash.js'
import { PAYMENT_COMPLETED, paymentStatusType, paymentType } from './shared/payments/index.js'
import { DAYS_MILLIS, comparePeriodStamps, dateToPeriodStamp, isPeriodStamp, plusOnePeriodLength } from './shared/time.js'
import { chatRoomAttributesType, inviteType } from './shared/types.js'
import proposals, { notifyAndArchiveProposal, proposalSettingsType, proposalType } from './shared/voting/proposals.js'
import votingRules, { RULE_DISAGREEMENT, RULE_PERCENTAGE, VOTE_AGAINST, VOTE_FOR, ruleType, voteType } from './shared/voting/rules.js'
function fetchInitKV (obj: Object, key: string, initialValue: any): any {
let value = obj[key]
if (!value) {
obj[key] = initialValue
value = obj[key]
}
return value
}
function initGroupProfile (joinedDate: string, joinedHeight: number, reference: string) {
return {
globalUsername: '', // TODO: this? e.g. groupincome:greg / namecoin:bob / ens:alice
joinedDate,
joinedHeight,
reference,
nonMonetaryContributions: [],
status: PROFILE_STATUS.ACTIVE,
departedDate: null,
incomeDetailsLastUpdatedDate: null
}
}
function initPaymentPeriod ({ meta, getters }) {
const start = getters.periodStampGivenDate(meta.createdDate)
return {
start,
end: plusOnePeriodLength(start, getters.groupSettings.distributionPeriodLength),
// this saved so that it can be used when creating a new payment
initialCurrency: getters.groupMincomeCurrency,
// TODO: should we also save the first period's currency exchange rate..?
// all payments during the period use this to set their exchangeRate
// see notes and code in groupIncomeAdjustedDistribution for details.
// TODO: for the currency change proposal, have it update the mincomeExchangeRate
// using .mincomeExchangeRate *= proposal.exchangeRate
mincomeExchangeRate: 1, // modified by proposals to change mincome currency
paymentsFrom: {}, // fromMemberID => toMemberID => Array<paymentHash>
// snapshot of adjusted distribution after each completed payment
// yes, it is possible a payment began in one period and completed in another
// in which case lastAdjustedDistribution for the previous period will be updated
lastAdjustedDistribution: null,
// snapshot of haveNeeds. made only when there are no payments
haveNeedsSnapshot: null
}
}
// NOTE: do not call any of these helper functions from within a getter b/c they modify state!
function clearOldPayments ({ contractID, state, getters }) {
const sortedPeriodKeys = Object.keys(state.paymentsByPeriod).sort()
// save two periods worth of payments, max
const archivingPayments = { paymentsByPeriod: {}, payments: {} }
while (sortedPeriodKeys.length > MAX_SAVED_PERIODS) {
const period = sortedPeriodKeys.shift()
archivingPayments.paymentsByPeriod[period] = cloneDeep(state.paymentsByPeriod[period])
for (const paymentHash of getters.paymentHashesForPeriod(period)) {
archivingPayments.payments[paymentHash] = cloneDeep(state.payments[paymentHash])
delete state.payments[paymentHash]
}
delete state.paymentsByPeriod[period]
}
// remove the waiting period from the archivingPayments to prevent it from appearing in Support History UI
delete archivingPayments.paymentsByPeriod[state.waitingPeriod]
sbp('gi.contracts/group/pushSideEffect', contractID,
['gi.contracts/group/archivePayments', contractID, archivingPayments]
)
}
function initFetchPeriodPayments ({ contractID, meta, state, getters }) {
const period = getters.periodStampGivenDate(meta.createdDate)
const periodPayments = fetchInitKV(state.paymentsByPeriod, period, initPaymentPeriod({ meta, getters }))
const previousPeriod = getters.periodBeforePeriod(period)
// Update the '.end' field of the previous in-memory period, if any.
if (previousPeriod in state.paymentsByPeriod) {
state.paymentsByPeriod[previousPeriod].end = period
}
clearOldPayments({ contractID, state, getters })
return periodPayments
}
function initGroupStreaks () {
return {
lastStreakPeriod: null,
fullMonthlyPledges: 0, // group streaks for 100% monthly payments - every pledging members have completed their payments
fullMonthlySupport: 0, // group streaks for 100% monthly supports - total amount of pledges done is equal to the group's monthly contribution goal
onTimePayments: {}, // { memberID: number, ... }
missedPayments: {}, // { memberID: number, ... }
noVotes: {} // { memberID: number, ... }
}
}
// this function is called each time a payment is completed or a user adjusts their income details.
// TODO: call also when mincome is adjusted
function updateCurrentDistribution ({ contractID, meta, state, getters }) {
const curPeriodPayments = initFetchPeriodPayments({ contractID, meta, state, getters })
const period = getters.periodStampGivenDate(meta.createdDate)
const noPayments = Object.keys(curPeriodPayments.paymentsFrom).length === 0
// update distributionDate if we've passed into the next period
if (comparePeriodStamps(period, getters.groupSettings.distributionDate) > 0) {
updateGroupStreaks({ state, getters })
getters.groupSettings.distributionDate = period
}
// save haveNeeds if there are no payments or the haveNeeds haven't been saved yet
if (noPayments || !curPeriodPayments.haveNeedsSnapshot) {
curPeriodPayments.haveNeedsSnapshot = getters.haveNeedsForThisPeriod(period)
}
// if there are payments this period, save the adjusted distribution
if (!noPayments) {
updateAdjustedDistribution({ period, getters })
}
}
function updateAdjustedDistribution ({ period, getters }) {
const payments = getters.groupPeriodPayments[period]
if (payments && payments.haveNeedsSnapshot) {
const minimize = getters.groupSettings.minimizeDistribution
// IMPORTANT! This code must be kept in sync with updateAdjustedDistribution!
// TODO: see if it's possible to DRY this with the code inside of updateAdjustedDistribution
payments.lastAdjustedDistribution = adjustedDistribution({
distribution: unadjustedDistribution({ haveNeeds: payments.haveNeedsSnapshot, minimize }),
payments: getters.paymentsForPeriod(period),
dueOn: getters.dueDateForPeriod(period)
}).filter(todo => {
// only return todos for active members
return getters.groupProfile(todo.toMemberID).status === PROFILE_STATUS.ACTIVE
})
}
}
function memberLeaves ({ memberID, dateLeft, heightLeft, ourselvesLeaving }, { contractID, meta, state, getters }) {
if (!state.profiles[memberID] || state.profiles[memberID].status !== PROFILE_STATUS.ACTIVE) {
throw new Error(`[gi.contracts/group memberLeaves] Can't remove non-exisiting member ${memberID}`)
}
state.profiles[memberID].status = PROFILE_STATUS.REMOVED
state.profiles[memberID].departedDate = dateLeft
state.profiles[memberID].departedHeight = heightLeft
// remove any todos for this member from the adjusted distribution
updateCurrentDistribution({ contractID, meta, state, getters })
Object.keys(state.chatRooms).forEach((chatroomID) => {
removeGroupChatroomProfile(state, chatroomID, memberID, ourselvesLeaving)
})
// When a member is leaving, we need to mark the CSK and the CEK as needing
// to be rotated. Later, this will be used by 'gi.contracts/group/rotateKeys'
// (to actually perform the rotation) and Chelonia (to unset the flag if
// they are rotated by somebody else)
// TODO: Improve this API. Developers should not modify state that is managed
// by Chelonia.
// Example: sbp('chelonia/contract/markKeyForRevocation', contractID, 'csk')
if (!state._volatile) state['_volatile'] = Object.create(null)
if (!state._volatile.pendingKeyRevocations) state._volatile['pendingKeyRevocations'] = Object.create(null)
const CSKid = findKeyIdByName(state, 'csk')
const CEKid = findKeyIdByName(state, 'cek')
state._volatile.pendingKeyRevocations[CSKid] = true
state._volatile.pendingKeyRevocations[CEKid] = true
}
function isActionNewerThanUserJoinedDate (height: number, userProfile: ?Object): boolean {
// A util function that checks if an action (or event) in a group occurred after a particular user joined a group.
// This is used mostly for checking if a notification should be sent for that user or not.
// e.g.) user-2 who joined a group later than user-1 (who is the creator of the group) doesn't need to receive
// 'MEMBER_ADDED' notification for user-1.
// In some situations, userProfile is undefined, for example, when inviteAccept is called in
// certain situations. So we need to check for that here.
if (!userProfile) {
return false
}
return userProfile.status === PROFILE_STATUS.ACTIVE && userProfile.joinedHeight < height
}
function updateGroupStreaks ({ state, getters }) {
const streaks = fetchInitKV(state, 'streaks', initGroupStreaks())
const cPeriod = getters.groupSettings.distributionDate
const thisPeriodPayments = getters.groupPeriodPayments[cPeriod]
const noPaymentsAtAll = !thisPeriodPayments
if (streaks.lastStreakPeriod === cPeriod) return
else {
streaks['lastStreakPeriod'] = cPeriod
}
// IMPORTANT! This code must be kept in sync with updateAdjustedDistribution!
// TODO: see if it's possible to DRY this with the code inside of updateAdjustedDistribution
const thisPeriodDistribution = thisPeriodPayments?.lastAdjustedDistribution || adjustedDistribution({
distribution: unadjustedDistribution({
haveNeeds: getters.haveNeedsForThisPeriod(cPeriod),
minimize: getters.groupSettings.minimizeDistribution
}) || [],
payments: getters.paymentsForPeriod(cPeriod),
dueOn: getters.dueDateForPeriod(cPeriod)
}).filter(todo => {
return getters.groupProfile(todo.toMemberID).status === PROFILE_STATUS.ACTIVE
})
// --- update 'fullMonthlyPledgesCount' streak ---
// if the group has made 100% pledges in this period, +1 the streak value.
// or else, reset the value to '0'
streaks['fullMonthlyPledges'] =
noPaymentsAtAll
? 0
: thisPeriodDistribution.length === 0
? streaks.fullMonthlyPledges + 1
: 0
const thisPeriodPaymentDetails = getters.paymentsForPeriod(cPeriod)
const thisPeriodHaveNeeds = thisPeriodPayments?.haveNeedsSnapshot || getters.haveNeedsForThisPeriod(cPeriod)
const filterMyItems = (array, member) => array.filter(item => item.fromMemberID === member)
const isPledgingMember = member => thisPeriodHaveNeeds.some(entry => entry.memberID === member && entry.haveNeed > 0)
// --- update 'fullMonthlySupport' streak. ---
const totalContributionGoal = thisPeriodHaveNeeds.reduce(
(total, item) => item.haveNeed < 0 ? total + (-1 * item.haveNeed) : total, 0
)
const totalPledgesDone = thisPeriodPaymentDetails.reduce(
(total, paymentItem) => paymentItem.amount + total, 0
)
const fullMonthlySupportCurrent = fetchInitKV(streaks, 'fullMonthlySupport', 0)
streaks['fullMonthlySupport'] =
totalPledgesDone > 0 && totalPledgesDone >= totalContributionGoal ? fullMonthlySupportCurrent + 1 : 0
// --- update 'onTimePayments' & 'missedPayments' streaks for 'pledging' members of the group ---
for (const memberID in getters.groupProfiles) {
if (!isPledgingMember(memberID)) continue
// 1) update 'onTimePayments'
const myMissedPaymentsInThisPeriod = filterMyItems(thisPeriodDistribution, memberID)
const userCurrentStreak = fetchInitKV(streaks.onTimePayments, memberID, 0)
streaks.onTimePayments[memberID] =
noPaymentsAtAll
? 0
: myMissedPaymentsInThisPeriod.length === 0 &&
filterMyItems(thisPeriodPaymentDetails, memberID).every(p => p.isLate === false)
// check-1. if the user made all the pledgeds assigned to them in this period.
// check-2. all those payments by the user were done on time.
? userCurrentStreak + 1
: 0
// 2) update 'missedPayments'
const myMissedPaymentsStreak = fetchInitKV(streaks.missedPayments, memberID, 0)
streaks.missedPayments[memberID] =
noPaymentsAtAll
? myMissedPaymentsStreak + 1
: myMissedPaymentsInThisPeriod.length >= 1
? myMissedPaymentsStreak + 1
: 0
}
}
const removeGroupChatroomProfile = (state, chatRoomID, memberID, ourselvesLeaving) => {
if (!state.chatRooms[chatRoomID].members[memberID]) return
state.chatRooms[chatRoomID].members[memberID].status = PROFILE_STATUS.REMOVED
}
const leaveChatRoomAction = async (groupID, state, chatRoomID, memberID, actorID, leavingGroup) => {
const sendingData = leavingGroup || actorID !== memberID
? { memberID }
: {}
if (state?.chatRooms?.[chatRoomID]?.members?.[memberID]?.status !== PROFILE_STATUS.REMOVED) {
return
}
const extraParams = {}
// When a group is being left, we want to also leave chatrooms,
// including private chatrooms. Since the user issuing the action
// may not be a member of the chatroom, we use the group's CSK
// unconditionally in this situation, which should be a key in the
// chatroom (either the CSK or the groupKey)
if (leavingGroup) {
const encryptionKeyId = await sbp('chelonia/contract/currentKeyIdByName', state, 'cek', true)
const signingKeyId = await sbp('chelonia/contract/currentKeyIdByName', state, 'csk', true)
// If we don't have a CSK, it is because we've already been removed.
// Proceeding would cause an error
if (!signingKeyId) {
return
}
// Set signing key to the CEK; this allows for managing joining and leaving
// the chatroom transparently to group members
extraParams.encryptionKeyId = encryptionKeyId
// Set signing key to the CSK; this allows group members to remove members
// from chatrooms they're not part of (e.g., when a group member is removed)
extraParams.signingKeyId = signingKeyId
// Explicitly opt out of inner signatures. By default, actions will be signed
// by the currently logged in user.
extraParams.innerSigningContractID = null
}
sbp('gi.actions/chatroom/leave', {
contractID: chatRoomID,
data: sendingData,
...extraParams
}).catch((e) => {
if (
leavingGroup &&
(e?.name === 'ChelErrorSignatureKeyNotFound' || (
e?.name === 'GIErrorUIRuntimeError' &&
(
['ChelErrorSignatureKeyNotFound', 'GIErrorMissingSigningKeyError'].includes(e?.cause?.name) ||
e?.cause?.name === 'GIChatroomNotMemberError'
)
))
) {
// This is fine; it just means we were removed by someone else
return
}
console.warn('[gi.contracts/group] Error sending chatroom leave action', e)
})
}
const leaveAllChatRoomsUponLeaving = (groupID, state, memberID, actorID) => {
const chatRooms = state.chatRooms
return Promise.all(Object.keys(chatRooms)
.filter(cID => chatRooms[cID].members?.[memberID]?.status === PROFILE_STATUS.REMOVED)
.map((chatRoomID) => leaveChatRoomAction(
groupID,
state,
chatRoomID,
memberID,
actorID,
true
))
)
}
export const actionRequireActiveMember = (next: Function): Function => (data, props) => {
const innerSigningContractID = props.message.innerSigningContractID
if (!innerSigningContractID || innerSigningContractID === props.contractID) {
throw new Error('Missing inner signature')
}
return next(data, props)
}
export const GIGroupAlreadyJoinedError: typeof Error = ChelErrorGenerator('GIGroupAlreadyJoinedError')
export const GIGroupNotJoinedError: typeof Error = ChelErrorGenerator('GIGroupNotJoinedError')
sbp('chelonia/defineContract', {
name: 'gi.contracts/group',
metadata: {
validate: objectOf({
createdDate: string
}),
async create () {
return {
createdDate: await fetchServerTime()
}
}
},
// These getters are restricted only to the contract's state.
// Do not access state outside the contract state inside of them.
// For example, if the getter you use tries to access `state.loggedIn`,
// that will break the `latestContractState` function in state.js.
// It is only safe to access state outside of the contract in a contract action's
// `sideEffect` function (as long as it doesn't modify contract state)
getters: {
// we define `currentGroupState` here so that we can redefine it in state.js
// so that we can re-use these getter definitions in state.js since they are
// compatible with Vuex getter definitions.
// Here `state` refers to the individual group contract's state, the equivalent
// of `vuexRootState[someGroupContractID]`.
currentGroupState (state) {
return state
},
currentGroupLastLoggedIn () {
return {}
},
...groupGetters
},
// NOTE: All mutations must be atomic in their edits of the contract state.
// THEY ARE NOT to farm out any further mutations through the async actions!
actions: {
// this is the constructor
'gi.contracts/group': {
validate: objectMaybeOf({
settings: objectMaybeOf({
// TODO: add 'groupPubkey'
groupName: stringMax(GROUP_NAME_MAX_CHAR, 'groupName'),
groupPicture: unionOf(string, objectOf({
manifestCid: stringMax(MAX_HASH_LEN, 'manifestCid'),
downloadParams: optional(object)
})),
sharedValues: stringMax(GROUP_DESCRIPTION_MAX_CHAR, 'sharedValues'),
mincomeAmount: numberRange(1, GROUP_MINCOME_MAX),
mincomeCurrency: stringMax(GROUP_CURRENCY_MAX_CHAR, 'mincomeCurrency'),
distributionDate: validatorFrom(isPeriodStamp),
distributionPeriodLength: numberRange(1 * DAYS_MILLIS, GROUP_DISTRIBUTION_PERIOD_MAX_DAYS * DAYS_MILLIS),
minimizeDistribution: boolean,
proposals: objectOf({
[PROPOSAL_INVITE_MEMBER]: proposalSettingsType,
[PROPOSAL_REMOVE_MEMBER]: proposalSettingsType,
[PROPOSAL_GROUP_SETTING_CHANGE]: proposalSettingsType,
[PROPOSAL_PROPOSAL_SETTING_CHANGE]: proposalSettingsType,
[PROPOSAL_GENERIC]: proposalSettingsType
})
})
}),
process ({ data, meta, contractID }, { state, getters }) {
// TODO: checkpointing: https://github.com/okTurtles/group-income/issues/354
const initialState = merge({
payments: {},
paymentsByPeriod: {},
thankYousFrom: {}, // { fromMember1: { toMember1: msg1, toMember2: msg2, ... }, fromMember2: {}, ... }
invites: {},
proposals: {}, // hashes => {} TODO: this, see related TODOs in GroupProposal
settings: {
distributionPeriodLength: 30 * DAYS_MILLIS,
inviteExpiryOnboarding: INVITE_EXPIRES_IN_DAYS.ON_BOARDING,
inviteExpiryProposal: INVITE_EXPIRES_IN_DAYS.PROPOSAL,
allowPublicChannels: false
},
streaks: initGroupStreaks(),
profiles: {},
chatRooms: {},
totalPledgeAmount: 0
}, data)
for (const key in initialState) {
state[key] = initialState[key]
}
initFetchPeriodPayments({ contractID, meta, state, getters })
// remember the waiting period so tha we can skip archiving it (hack for hiding it in the Support History)
state.waitingPeriod = getters.periodStampGivenDate(meta.createdDate)
},
sideEffect ({ contractID }, { state }) {
if (!state.generalChatRoomId) {
// create a 'General' chatroom contract
sbp('chelonia/queueInvocation', contractID, async () => {
const state = await sbp('chelonia/contract/state', contractID)
if (!state || state.generalChatRoomId) return
const CSKid = findKeyIdByName(state, 'csk')
const CEKid = findKeyIdByName(state, 'cek')
// create a 'General' chatroom contract
sbp('gi.actions/group/addChatRoom', {
contractID,
data: {
attributes: {
name: CHATROOM_GENERAL_NAME,
type: CHATROOM_TYPES.GROUP,
description: '',
privacyLevel: CHATROOM_PRIVACY_LEVEL.GROUP
}
},
signingKeyId: CSKid,
encryptionKeyId: CEKid,
// The #General chatroom does not have an inner signature as it's part
// of the group creation process
innerSigningContractID: null
}).catch((e) => {
console.error(`[gi.contracts/group/sideEffect] Error creating #General chatroom for ${contractID} (unable to send action)`, e)
})
}).catch((e) => {
console.error(`[gi.contracts/group/sideEffect] Error creating #General chatroom for ${contractID}`, e)
})
}
}
},
'gi.contracts/group/payment': {
validate: actionRequireActiveMember(objectMaybeOf({
// TODO: how to handle donations to okTurtles?
// TODO: how to handle payments to groups or users outside of this group?
toMemberID: stringMax(MAX_HASH_LEN, 'toMemberID'),
amount: numberRange(0, GROUP_MINCOME_MAX),
currencyFromTo: tupleOf(string, string), // must be one of the keys in currencies.js (e.g. USD, EUR, etc.) TODO: handle old clients not having one of these keys, see OP_PROTOCOL_UPGRADE https://github.com/okTurtles/group-income/issues/603
// multiply 'amount' by 'exchangeRate', which must always be
// based on the initialCurrency of the period in which this payment was created.
// it is then further multiplied by the period's 'mincomeExchangeRate', which
// is modified if any proposals pass to change the mincomeCurrency
exchangeRate: numberRange(0, GROUP_MINCOME_MAX),
txid: stringMax(MAX_HASH_LEN, 'txid'),
status: paymentStatusType,
paymentType: paymentType,
details: optional(object),
memo: optional(stringMax(MAX_MEMO_LEN, 'memo'))
})),
process ({ data, meta, hash, contractID, height, innerSigningContractID }, { state, getters }) {
if (data.status === PAYMENT_COMPLETED) {
console.error(`payment: payment ${hash} cannot have status = 'completed'!`, { data, meta, hash })
throw new Errors.GIErrorIgnoreAndBan('payments cannot be instantly completed!')
}
state.payments[hash] = {
data: {
...data,
fromMemberID: innerSigningContractID,
groupMincome: getters.groupMincomeAmount
},
height,
meta,
history: [[meta.createdDate, hash]]
}
const { paymentsFrom } = initFetchPeriodPayments({ contractID, meta, state, getters })
const fromMemberID = fetchInitKV(paymentsFrom, innerSigningContractID, {})
const toMemberID = fetchInitKV(fromMemberID, data.toMemberID, [])
toMemberID.push(hash)
// TODO: handle completed payments here too! (for manual payment support)
}
},
'gi.contracts/group/paymentUpdate': {
validate: actionRequireActiveMember(objectMaybeOf({
paymentHash: stringMax(MAX_HASH_LEN, 'paymentHash'),
updatedProperties: objectMaybeOf({
status: paymentStatusType,
details: object,
memo: stringMax(MAX_MEMO_LEN, 'memo')
})
})),
process ({ data, meta, hash, contractID, innerSigningContractID }, { state, getters }) {
// TODO: we don't want to keep a history of all payments in memory all the time
// https://github.com/okTurtles/group-income/issues/426
const payment = state.payments[data.paymentHash]
// TODO: move these types of validation errors into the validate function so
// that they can be done before sending as well as upon receiving
if (!payment) {
console.error(`paymentUpdate: no payment ${data.paymentHash}`, { data, meta, hash })
throw new Errors.GIErrorIgnoreAndBan('paymentUpdate without existing payment')
}
// if the payment is being modified by someone other than the person who sent or received it, throw an exception
if (innerSigningContractID !== payment.data.fromMemberID && innerSigningContractID !== payment.data.toMemberID) {
console.error(`paymentUpdate: bad member ${innerSigningContractID} != ${payment.data.fromMemberID} != ${payment.data.toMemberID}`, { data, meta, hash })
throw new Errors.GIErrorIgnoreAndBan('paymentUpdate from bad user!')
}
payment.history.push([meta.createdDate, hash])
merge(payment.data, data.updatedProperties)
// we update "this period"'s snapshot 'lastAdjustedDistribution' on each completed payment
if (data.updatedProperties.status === PAYMENT_COMPLETED) {
payment.data.completedDate = meta.createdDate
// update the current distribution unless this update is for a payment from the previous period
const updatePeriodStamp = getters.periodStampGivenDate(meta.createdDate)
const paymentPeriodStamp = getters.periodStampGivenDate(payment.meta.createdDate)
if (comparePeriodStamps(updatePeriodStamp, paymentPeriodStamp) > 0) {
updateAdjustedDistribution({ period: paymentPeriodStamp, getters })
} else {
updateCurrentDistribution({ contractID, meta, state, getters })
}
// NOTE: if 'PAYMENT_REVERSED' is implemented, subtract
// the amount from 'totalPledgeAmount'.
const currentTotalPledgeAmount = fetchInitKV(state, 'totalPledgeAmount', 0)
state.totalPledgeAmount = currentTotalPledgeAmount + payment.data.amount
}
},
sideEffect ({ meta, contractID, height, data, innerSigningContractID }, { state, getters }) {
if (data.updatedProperties.status === PAYMENT_COMPLETED) {
const { loggedIn } = sbp('state/vuex/state')
const payment = state.payments[data.paymentHash]
if (loggedIn.identityContractID === payment.data.toMemberID) {
const myProfile = getters.groupProfile(loggedIn.identityContractID)
if (isActionNewerThanUserJoinedDate(height, myProfile)) {
sbp('gi.notifications/emit', 'PAYMENT_RECEIVED', {
createdDate: meta.createdDate,
groupID: contractID,
creatorID: innerSigningContractID,
paymentHash: data.paymentHash,
amount: getters.withGroupCurrency(payment.data.amount)
})
}
}
}
}
},
'gi.contracts/group/sendPaymentThankYou': {
validate: actionRequireActiveMember(objectOf({
toMemberID: stringMax(MAX_HASH_LEN, 'toMemberID'),
memo: stringMax(MAX_MEMO_LEN, 'memo')
})),
process ({ data, innerSigningContractID }, { state }) {
const fromMemberID = fetchInitKV(state.thankYousFrom, innerSigningContractID, {})
fromMemberID[data.toMemberID] = data.memo
},
sideEffect ({ contractID, meta, height, data, innerSigningContractID }, { getters }) {
const { loggedIn } = sbp('state/vuex/state')
if (data.toMemberID === loggedIn.identityContractID) {
const myProfile = getters.groupProfile(loggedIn.identityContractID)
if (isActionNewerThanUserJoinedDate(height, myProfile)) {
sbp('gi.notifications/emit', 'PAYMENT_THANKYOU_SENT', {
createdDate: meta.createdDate,
groupID: contractID,
fromMemberID: innerSigningContractID,
toMemberID: data.toMemberID
})
}
}
}
},
'gi.contracts/group/proposal': {
validate: actionRequireActiveMember((data, { state }) => {
objectOf({
proposalType: proposalType,
proposalData: object, // data for Vue widgets
votingRule: ruleType,
expires_date_ms: numberRange(0, Number.MAX_SAFE_INTEGER) // calculate by grabbing proposal expiry from group properties and add to `meta.createdDate`
})(data)
const dataToCompare = omit(data.proposalData, ['reason'])
// Validate this isn't a duplicate proposal
for (const hash in state.proposals) {
const prop = state.proposals[hash]
if (prop.status !== STATUS_OPEN || prop.data.proposalType !== data.proposalType) {
continue
}
if (deepEqualJSONType(omit(prop.data.proposalData, ['reason']), dataToCompare)) {
throw new TypeError(L('There is an identical open proposal.'))
}
// TODO - verify if type of proposal already exists (SETTING_CHANGE).
}
}),
process ({ data, meta, hash, height, innerSigningContractID }, { state }) {
state.proposals[hash] = {
data,
meta,
height,
creatorID: innerSigningContractID,
votes: { [innerSigningContractID]: VOTE_FOR },
status: STATUS_OPEN,
notifiedBeforeExpire: false,
payload: null // set later by group/proposalVote
}
// TODO: save all proposals disk so that we only keep open proposals in memory
// TODO: create a global timer to auto-pass/archive expired votes
// make sure to set that proposal's status as STATUS_EXPIRED if it's expired
},
sideEffect ({ contractID, meta, hash, data, height, innerSigningContractID }, { getters }) {
const { loggedIn } = sbp('state/vuex/state')
const typeToSubTypeMap = {
[PROPOSAL_INVITE_MEMBER]: 'ADD_MEMBER',
[PROPOSAL_REMOVE_MEMBER]: 'REMOVE_MEMBER',
[PROPOSAL_GROUP_SETTING_CHANGE]: {
mincomeAmount: 'CHANGE_MINCOME',
distributionDate: 'CHANGE_DISTRIBUTION_DATE'
}[data.proposalData.setting],
[PROPOSAL_PROPOSAL_SETTING_CHANGE]: 'CHANGE_VOTING_RULE',
[PROPOSAL_GENERIC]: 'GENERIC'
}
const myProfile = getters.groupProfile(loggedIn.identityContractID)
if (isActionNewerThanUserJoinedDate(height, myProfile)) {
sbp('gi.notifications/emit', 'NEW_PROPOSAL', {
createdDate: meta.createdDate,
groupID: contractID,
creatorID: innerSigningContractID,
proposalHash: hash,
subtype: typeToSubTypeMap[data.proposalType]
})
}
}
},
'gi.contracts/group/proposalVote': {
validate: actionRequireActiveMember(objectOf({
proposalHash: stringMax(MAX_HASH_LEN, 'proposalHash'),
vote: voteType,
passPayload: optional(unionOf(object, string)) // TODO: this, somehow we need to send an OP_KEY_ADD GIMessage to add a generated once-only writeonly message public key to the contract, and (encrypted) include the corresponding invite link, also, we need all clients to verify that this message/operation was valid to prevent a hacked client from adding arbitrary OP_KEY_ADD messages, and automatically ban anyone generating such messages
})),
async process (message, { state, getters }) {
const { data, hash, meta, innerSigningContractID } = message
const proposal = state.proposals[data.proposalHash]
if (!proposal) {
// https://github.com/okTurtles/group-income/issues/602
console.error(`proposalVote: no proposal for ${data.proposalHash}!`, { data, meta, hash })
throw new Errors.GIErrorIgnoreAndBan('proposalVote without existing proposal')
}
proposal.votes[innerSigningContractID] = data.vote
// TODO: handle vote pass/fail
// check if proposal is expired, if so, ignore (but log vote)
if (new Date(meta.createdDate).getTime() > proposal.data.expires_date_ms) {
console.warn('proposalVote: vote on expired proposal!', { proposal, data, meta })
// TODO: display warning or something
return
}
// see if this is a deciding vote
const result = votingRules[proposal.data.votingRule](state, proposal.data.proposalType, proposal.votes)
if (result === VOTE_FOR || result === VOTE_AGAINST) {
// handles proposal pass or fail, will update proposal.status accordingly
proposal['dateClosed'] = meta.createdDate
await proposals[proposal.data.proposalType][result](state, message)
// update 'streaks.noVotes' which records the number of proposals that each member did NOT vote for
const votedMemberIDs = Object.keys(proposal.votes)
for (const memberID of getters.groupMembersByContractID) {
const memberCurrentStreak = fetchInitKV(getters.groupStreaks.noVotes, memberID, 0)
const memberHasVoted = votedMemberIDs.includes(memberID)
getters.groupStreaks.noVotes[memberID] = memberHasVoted ? 0 : memberCurrentStreak + 1
}
}
}
},
'gi.contracts/group/proposalCancel': {
validate: actionRequireActiveMember(objectOf({
proposalHash: stringMax(MAX_HASH_LEN, 'proposalHash')
})),
process ({ data, meta, contractID, innerSigningContractID, height }, { state }) {
const proposal = state.proposals[data.proposalHash]
if (!proposal) {
// https://github.com/okTurtles/group-income/issues/602
console.error(`proposalCancel: no proposal for ${data.proposalHash}!`, { data, meta })
throw new Errors.GIErrorIgnoreAndBan('proposalVote without existing proposal')
} else if (proposal.creatorID !== innerSigningContractID) {
console.error(`proposalCancel: proposal ${data.proposalHash} belongs to ${proposal.creatorID} not ${innerSigningContractID}!`, { data, meta })
throw new Errors.GIErrorIgnoreAndBan('proposalWithdraw for wrong user!')
}
proposal['status'] = STATUS_CANCELLED
proposal['dateClosed'] = meta.createdDate
notifyAndArchiveProposal({ state, proposalHash: data.proposalHash, proposal, contractID, meta, height })
}
},
'gi.contracts/group/markProposalsExpired': {
validate: actionRequireActiveMember(objectOf({
proposalIds: arrayOf(stringMax(MAX_HASH_LEN))
})),
process ({ data, meta, contractID, height }, { state }) {
if (data.proposalIds.length) {
for (const proposalId of data.proposalIds) {
const proposal = state.proposals[proposalId]
if (proposal) {
proposal['status'] = STATUS_EXPIRED
proposal['dateClosed'] = meta.createdDate
notifyAndArchiveProposal({ state, proposalHash: proposalId, proposal, contractID, meta, height })
}
}
}
}
},
'gi.contracts/group/notifyExpiringProposals': {
validate: actionRequireActiveMember(objectOf({
proposalIds: arrayOf(string)
})),
process ({ data }, { state }) {
for (const proposalId of data.proposalIds) {
state.proposals[proposalId]['notifiedBeforeExpire'] = true
}
},
sideEffect ({ data, height, contractID }, { state, getters }) {
const { loggedIn } = sbp('state/vuex/state')
const myProfile = getters.groupProfile(loggedIn.identityContractID)
if (isActionNewerThanUserJoinedDate(height, myProfile)) {
for (const proposalId of data.proposalIds) {
const proposal = state.proposals[proposalId]
sbp('gi.notifications/emit', 'PROPOSAL_EXPIRING', {
groupID: contractID, proposal, proposalId
})
}
}
}
},
'gi.contracts/group/removeMember': {
validate: actionRequireActiveMember((data, { state, getters, message: { innerSigningContractID, proposalHash } }) => {
objectOf({
memberID: optional(stringMax(MAX_HASH_LEN)), // member to remove
reason: optional(stringMax(GROUP_DESCRIPTION_MAX_CHAR)),
automated: optional(boolean)
})(data)
const memberToRemove = data.memberID || innerSigningContractID
const membersCount = getters.groupMembersCount
const isGroupCreator = innerSigningContractID === getters.currentGroupOwnerID
if (!state.profiles[memberToRemove]) {
throw new GIGroupNotJoinedError(L('Not part of the group.'))
}
if (membersCount === 1) {
throw new TypeError(L('Cannot remove the last member.'))
}
if (memberToRemove === innerSigningContractID) {
return true
}
if (isGroupCreator) {
return true
} else if (membersCount < 3) {
// In a small group only the creator can remove someone
// TODO: check whetherinnerSigningContractID has required admin permissions
throw new TypeError(L('Only the group creator can remove members.'))
} else {
// In a big group a removal can only happen through a proposal
// We don't need to do much validation as this attribute is only
// provided through a secure context. It's presence indicates that
// a proposal passed.
const proposal = state.proposals[proposalHash]
if (!proposal) {
// TODO this
throw new TypeError(L('Admin credentials needed and not implemented yet.'))
}
}
}),
process ({ data, meta, contractID, height, innerSigningContractID }, { state, getters }) {
const memberID = data.memberID || innerSigningContractID
const identityContractID = sbp('state/vuex/state').loggedIn?.identityContractID
if (memberID === identityContractID) {
const ourChatrooms = Object.entries(state?.chatRooms || {}).filter(([, state]: [string, Object]) => state.members[identityContractID]?.status === PROFILE_STATUS.ACTIVE).map(([cID]) => cID)
if (ourChatrooms.length) {
sbp('gi.contracts/group/pushSideEffect', contractID,
['gi.contracts/group/referenceTally', contractID, ourChatrooms, 'release'])
}
}
memberLeaves(
{ memberID, dateLeft: meta.createdDate, heightLeft: height, ourselvesLeaving: memberID === identityContractID },
{ contractID, meta, state, getters }
)
},
sideEffect ({ data, meta, contractID, height, innerSigningContractID, proposalHash }, { state, getters }) {
const memberID = data.memberID || innerSigningContractID
sbp('gi.contracts/group/referenceTally', contractID, memberID, 'release')
// Put this invocation at the end of a sync to ensure that leaving and re-joining works
sbp('chelonia/queueInvocation', contractID, () => sbp('gi.contracts/group/leaveGroup', {
data, meta, contractID, getters, height, innerSigningContractID, proposalHash
})).catch(e => {
console.warn(`[gi.contracts/group/removeMember/sideEffect] Error ${e.name} during queueInvocation for ${contractID}`, e)
})
}
},
'gi.contracts/group/invite': {
validate: actionRequireActiveMember(inviteType),
process ({ data }, { state }) {
state.invites[data.inviteKeyId] = data
}
},
'gi.contracts/group/inviteAccept': {
validate: actionRequireInnerSignature(objectOf({ reference: string })),
process ({ data, meta, height, innerSigningContractID }, { state }) {
if (state.profiles[innerSigningContractID]?.status === PROFILE_STATUS.ACTIVE) {
throw new Error(`[gi.contracts/group/inviteAccept] Existing members can't accept invites: ${innerSigningContractID}`)
}
state.profiles[innerSigningContractID] = initGroupProfile(meta.createdDate, height, data.reference)
// If we're triggered by handleEvent in state.js (and not latestContractState)
// then the asynchronous sideEffect function will get called next
// and we will subscribe to this new user's identity contract
},
// !! IMPORANT!!
// Actions here MUST NOT modify contract state!
// They MUST NOT call 'commit'!
// They should only coordinate the actions of outside contracts.
// Otherwise `latestContractState` and `handleEvent` will not produce same state!
sideEffect ({ meta, contractID, height, innerSigningContractID }) {
const { loggedIn } = sbp('state/vuex/state')
// subscribe to the contract of the new member
sbp('gi.contracts/group/referenceTally', contractID, innerSigningContractID, 'retain')
sbp('chelonia/queueInvocation', contractID, async () => {
const state = await sbp('chelonia/contract/state', contractID)
if (!state) {
console.info(`[gi.contracts/group/inviteAccept] Contract ${contractID} has been removed`)
return
}
const { profiles = {} } = state
if (profiles[innerSigningContractID].status !== PROFILE_STATUS.ACTIVE) {
return
}
const userID = loggedIn.identityContractID
// TODO: per #257 this will ,have to be encompassed in a recoverable transaction
// however per #610 that might be handled in handleEvent (?), or per #356 might not be needed
if (innerSigningContractID === userID) {
// we're the person who just accepted the group invite
// Add the group's CSK to our identity contract so that we can receive
// DMs.
await sbp('gi.actions/identity/addJoinDirectMessageKey', userID, contractID, 'csk')
const generalChatRoomId = state.generalChatRoomId
if (generalChatRoomId) {
// Join the general chatroom
if (state.chatRooms[generalChatRoomId]?.members?.[userID]?.status !== PROFILE_STATUS.ACTIVE) {
sbp('gi.actions/group/joinChatRoom', {
contractID,
data: { chatRoomID: generalChatRoomId }
}).catch((e) => {
// If already joined, ignore this error
if (e?.name === 'GIErrorUIRuntimeError' && e.cause?.name === 'GIGroupAlreadyJoinedError') return
console.error('Error while joining the #General chatroom', e)
const errMsg = L("Couldn't join the #{chatroomName} in the group. An error occurred: {error}", { chatroomName: CHATROOM_GENERAL_NAME, error: e?.message || e })
const promptOptions = {
heading: L('Error while joining a chatroom'),
question: errMsg,
primaryButton: L('Close')
}
sbp('gi.ui/prompt', promptOptions)
})
}
} else {
// avoid blocking the main thread
// eslint-disable-next-line require-await
(async () => {
alert(L("Couldn't join the #{chatroomName} in the group. Doesn't exist.", { chatroomName: CHATROOM_GENERAL_NAME }))
})()
}
sbp('okTurtles.events/emit', JOINED_GROUP, { identityContractID: userID, groupContractID: contractID })
} else if (isActionNewerThanUserJoinedDate(height, state?.profiles?.[userID])) {
sbp('gi.notifications/emit', 'MEMBER_ADDED', {
createdDate: meta.createdDate,
groupID: contractID,
memberID: innerSigningContractID
})
}
}).catch(e => {
console.error('[gi.contracts/group/inviteAccept/sideEffect]: An error occurred', e)
})
}
},
'gi.contracts/group/inviteRevoke': {
validate: actionRequireActiveMember((data, { state }) => {
objectOf({
inviteKeyId: stringMax(MAX_HASH_LEN, 'inviteKeyId')
})(data)
if (!state._vm.invites[data.inviteKeyId]) {
throw new TypeError(L('The link does not exist.'))
}
}),
process () {
// Handled by Chelonia
}
},
'gi.contracts/group/updateSettings': {
// OPTIMIZE: Make this custom validation function
// reusable accross other future validators
validate: actionRequireActiveMember((data, { getters, meta, message: { innerSigningContractID } }) => {
objectMaybeOf({
groupName: stringMax(GROUP_NAME_MAX_CHAR, 'groupName'),
groupPicture: unionOf(string, objectOf({
manifestCid: stringMax(MAX_HASH_LEN, 'manifestCid'),
downloadParams: optional(object)
})),
sharedValues: stringMax(GROUP_DESCRIPTION_MAX_CHAR, 'sharedValues'),
mincomeAmount: numberRange(Number.EPSILON, Number.MAX_VALUE),
mincomeCurrency: stringMax(GROUP_CURRENCY_MAX_CHAR, 'mincomeCurrency'),
distributionDate: string,
allowPublicChannels: boolean
})(data)