-
Notifications
You must be signed in to change notification settings - Fork 243
/
InstantDistributionAgreementV1.sol
1076 lines (951 loc) · 36.3 KB
/
InstantDistributionAgreementV1.sol
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
// SPDX-License-Identifier: AGPLv3
pragma solidity 0.7.6;
import {
IInstantDistributionAgreementV1,
ISuperfluidToken
} from "../interfaces/agreements/IInstantDistributionAgreementV1.sol";
import {
ISuperfluid,
ISuperfluidGovernance,
ISuperApp,
SuperAppDefinitions
}
from "../interfaces/superfluid/ISuperfluid.sol";
import { AgreementBase } from "./AgreementBase.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { UInt128SafeMath } from "../libs/UInt128SafeMath.sol";
import { AgreementLibrary } from "./AgreementLibrary.sol";
import { SlotsBitmapLibrary } from "./SlotsBitmapLibrary.sol";
contract InstantDistributionAgreementV1 is
AgreementBase,
IInstantDistributionAgreementV1
{
/*
E_NO_INDEX - index does not exist
E_INDEX_EXISTS - index already exists
E_INDEX_GROW - index value should grow
E_LOW_BALANCE - insufficient balance
E_SUBS_APPROVED subscription already approved
E_SUBS_NOT_APPROVED subscription not approved
E_NO_SUBS - subscription does not exist
E_NOT_ALLOWED - operation not allowed
*/
using SafeMath for uint256;
using SafeCast for uint256;
using UInt128SafeMath for uint128;
using SignedSafeMath for int256;
address public constant SLOTS_BITMAP_LIBRARY_ADDRESS = address(SlotsBitmapLibrary);
/// @dev Subscriber state slot id for storing subs bitmap
uint256 private constant _SUBSCRIBER_SUBS_BITMAP_STATE_SLOT_ID = 0;
/// @dev Publisher state slot id for storing its deposit amount
uint256 private constant _PUBLISHER_DEPOSIT_STATE_SLOT_ID = 1 << 32;
/// @dev Subscriber state slot id starting ptoint for subscription data
uint256 private constant _SUBSCRIBER_SUB_DATA_STATE_SLOT_ID_START = 1 << 128;
/// @dev Maximum number of subscriptions a subscriber can have
uint32 private constant _MAX_NUM_SUBS = 256;
/// @dev A special id that indicating the subscription is not approved yet
uint32 private constant _UNALLOCATED_SUB_ID = type(uint32).max;
/// @dev Agreement data for the index
struct IndexData {
uint128 indexValue;
uint128 totalUnitsApproved;
uint128 totalUnitsPending;
}
/// @dev Agreement data for the subscription
struct SubscriptionData {
uint32 subId;
address publisher;
uint32 indexId;
uint128 indexValue;
uint128 units;
}
/**************************************************************************
* ISuperAgreement interface
*************************************************************************/
/// @dev ISuperAgreement.realtimeBalanceOf implementation
function realtimeBalanceOf(
ISuperfluidToken token,
address account,
uint256 /*time*/
)
external view override
returns (
int256 dynamicBalance,
uint256 deposit,
uint256 owedDeposit
)
{
// as a subscriber
// read all subs and calculate the real-time balance
uint32[] memory slotIds;
bytes32[] memory sidList;
(slotIds, sidList) = _listSubscriptionIds(token, account);
for (uint32 i = 0; i < sidList.length; ++i) {
bool exist;
SubscriptionData memory sdata;
bytes32 iId;
{
uint32 subId = slotIds[i];
(exist, sdata) = _getSubscriptionData(token, sidList[i]);
assert(exist);
assert(sdata.subId == subId);
//require(exist, "IDA: E_NO_SUBS");
iId = token.getAgreementStateSlot(
address(this),
account,
_SUBSCRIBER_SUB_DATA_STATE_SLOT_ID_START + subId, 1)[0];
}
{
IndexData memory idata;
(exist, idata) = _getIndexData(token, iId);
assert(exist);
dynamicBalance = dynamicBalance.add(
int256(idata.indexValue - sdata.indexValue) * int256(sdata.units)
);
}
}
// as a publisher
// calculate the deposits due to pending subscriptions
deposit = _getPublisherDeposit(token, account);
owedDeposit = 0;
}
/**************************************************************************
* Index operations
*************************************************************************/
/// @dev IInstantDistributionAgreementV1.createIndex implementation
function createIndex(
ISuperfluidToken token,
uint32 indexId,
bytes calldata ctx
)
external override
returns(bytes memory newCtx)
{
ISuperfluid.Context memory context = AgreementLibrary.authorizeTokenAccess(token, ctx);
address publisher = context.msgSender;
bytes32 iId = _getPublisherId(publisher, indexId);
require(!_hasIndexData(token, iId), "IDA: E_INDEX_EXISTS");
token.createAgreement(iId, _encodeIndexData(IndexData(0, 0, 0)));
emit IndexCreated(token, publisher, indexId, context.userData);
// nothing to be recorded so far
newCtx = ctx;
}
/// @dev IInstantDistributionAgreementV1.getIndex implementation
function getIndex(
ISuperfluidToken token,
address publisher,
uint32 indexId
)
external view override
returns (
bool exist,
uint128 indexValue,
uint128 totalUnitsApproved,
uint128 totalUnitsPending)
{
IndexData memory idata;
bytes32 iId = _getPublisherId(publisher, indexId);
(exist, idata) = _getIndexData(token, iId);
if (exist) {
indexValue = idata.indexValue;
totalUnitsApproved = idata.totalUnitsApproved;
totalUnitsPending = idata.totalUnitsPending;
}
}
/// @dev IInstantDistributionAgreementV1.calculateDistribution implementation
function calculateDistribution(
ISuperfluidToken token,
address publisher,
uint32 indexId,
uint256 amount
)
external view override
returns(
uint256 actualAmount,
uint128 newIndexValue)
{
bytes32 iId = _getPublisherId(publisher, indexId);
(bool exist, IndexData memory idata) = _getIndexData(token, iId);
require(exist, "IDA: E_NO_INDEX");
uint256 totalUnits = uint256(idata.totalUnitsApproved + idata.totalUnitsPending);
uint128 indexDelta = (amount / totalUnits).toUint128();
newIndexValue = idata.indexValue.add(indexDelta, "IDA: E_OVERFLOW");
actualAmount = uint256(indexDelta).mul(totalUnits);
}
/// @dev IInstantDistributionAgreementV1.updateIndex implementation
function updateIndex(
ISuperfluidToken token,
uint32 indexId,
uint128 indexValue,
bytes calldata ctx
)
external override
returns(bytes memory newCtx)
{
ISuperfluid.Context memory context = AgreementLibrary.authorizeTokenAccess(token, ctx);
address publisher = context.msgSender;
(bytes32 iId, IndexData memory idata) = _loadIndexData(token, publisher, indexId);
require(indexValue >= idata.indexValue, "IDA: E_INDEX_GROW");
_updateIndex(token, publisher, indexId, iId, idata, indexValue, context.userData);
// nothing to be recorded so far
newCtx = ctx;
}
/// @dev IInstantDistributionAgreementV1.distribute implementation
function distribute(
ISuperfluidToken token,
uint32 indexId,
uint256 amount,
bytes calldata ctx
)
external override
returns(bytes memory newCtx)
{
ISuperfluid.Context memory context = AgreementLibrary.authorizeTokenAccess(token, ctx);
address publisher = context.msgSender;
(bytes32 iId, IndexData memory idata) = _loadIndexData(token, publisher, indexId);
uint128 indexDelta = (
amount /
uint256(idata.totalUnitsApproved + idata.totalUnitsPending)
).toUint128();
_updateIndex(token, publisher, indexId, iId, idata, idata.indexValue + indexDelta, context.userData);
// nothing to be recorded so far
newCtx = ctx;
}
function _updateIndex(
ISuperfluidToken token,
address publisher,
uint32 indexId,
bytes32 iId,
IndexData memory idata,
uint128 newIndexValue,
bytes memory userData
)
private
{
// - settle the publisher balance INSTANT-ly (ding ding ding, IDA)
// - adjust static balance directly
token.settleBalance(publisher,
(-int256(newIndexValue - idata.indexValue)).mul(int256(idata.totalUnitsApproved)));
// - adjust the publisher's deposit amount
_adjustPublisherDeposit(token, publisher,
int256(newIndexValue - idata.indexValue).mul(int256(idata.totalUnitsPending)));
// adjust the publisher's index data
uint128 oldIndexValue = idata.indexValue;
idata.indexValue = newIndexValue;
token.updateAgreementData(iId, _encodeIndexData(idata));
emit IndexUpdated(
token,
publisher,
indexId,
oldIndexValue,
newIndexValue,
idata.totalUnitsPending,
idata.totalUnitsApproved,
userData);
// check account solvency
require(!token.isAccountCriticalNow(publisher), "IDA: E_LOW_BALANCE");
}
function _loadIndexData(
ISuperfluidToken token,
address publisher,
uint32 indexId)
private view
returns (
bytes32 iId,
IndexData memory idata
)
{
bool exist;
iId = _getPublisherId(publisher, indexId);
(exist, idata) = _getIndexData(token, iId);
require(exist, "IDA: E_NO_INDEX");
}
/**************************************************************************
* Subscription operations
*************************************************************************/
// Stack variables to avoid stack too deep errors in some functions
// solhint-disable-next-line contract-name-camelcase
struct _SubscriptionOperationVars {
bytes32 iId;
bool subscriptionExists;
bytes32 sId;
IndexData idata;
SubscriptionData sdata;
bytes cbdata;
}
/// @dev IInstantDistributionAgreementV1.approveSubscription implementation
function approveSubscription(
ISuperfluidToken token,
address publisher,
uint32 indexId,
bytes calldata ctx
)
external override
returns(bytes memory newCtx)
{
_SubscriptionOperationVars memory vars;
AgreementLibrary.CallbackInputs memory cbStates;
address subscriber;
bytes memory userData;
{
ISuperfluid.Context memory context = AgreementLibrary.authorizeTokenAccess(token, ctx);
subscriber = context.msgSender;
userData = context.userData;
}
(
vars.iId,
vars.sId,
vars.idata,
vars.subscriptionExists,
vars.sdata
) = _loadAllData(token, publisher, subscriber, indexId, false);
if (vars.subscriptionExists) {
// required condition check
require(vars.sdata.subId == _UNALLOCATED_SUB_ID, "IDA: E_SUBS_APPROVED");
}
newCtx = ctx;
cbStates = AgreementLibrary.createCallbackInputs(
token,
publisher,
vars.sId,
"");
if (!vars.subscriptionExists) {
cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_CREATED_NOOP;
vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, newCtx);
vars.sdata = SubscriptionData({
publisher: publisher,
indexId: indexId,
subId: 0,
units: 0,
indexValue: vars.idata.indexValue
});
// add to subscription list of the subscriber
vars.sdata.subId = _findAndFillSubsBitmap(token, subscriber, vars.iId);
token.createAgreement(vars.sId, _encodeSubscriptionData(vars.sdata));
cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_CREATED_NOOP;
AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx);
} else {
cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_UPDATED_NOOP;
vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, newCtx);
int balanceDelta = int256(vars.idata.indexValue - vars.sdata.indexValue) * int256(vars.sdata.units);
// update publisher data and adjust publisher's deposits
vars.idata.totalUnitsApproved += vars.sdata.units;
vars.idata.totalUnitsPending -= vars.sdata.units;
token.updateAgreementData(vars.iId, _encodeIndexData(vars.idata));
_adjustPublisherDeposit(token, publisher, -balanceDelta);
token.settleBalance(publisher, -balanceDelta);
// update subscription data and adjust subscriber's balance
token.settleBalance(subscriber, balanceDelta);
vars.sdata.indexValue = vars.idata.indexValue;
vars.sdata.subId = _findAndFillSubsBitmap(token, subscriber, vars.iId);
token.updateAgreementData(vars.sId, _encodeSubscriptionData(vars.sdata));
cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_UPDATED_NOOP;
AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx);
}
// can index up to three words, hence splitting into two events from publisher or subscriber's view.
emit IndexSubscribed(token, publisher, indexId, subscriber, userData);
emit SubscriptionApproved(token, subscriber, publisher, indexId, userData);
}
/// @dev IInstantDistributionAgreementV1.revokeSubscription implementation
function revokeSubscription(
ISuperfluidToken token,
address publisher,
uint32 indexId,
bytes calldata ctx
)
external override
returns(bytes memory newCtx)
{
_SubscriptionOperationVars memory vars;
AgreementLibrary.CallbackInputs memory cbStates;
address subscriber;
bytes memory userData;
{
ISuperfluid.Context memory context = AgreementLibrary.authorizeTokenAccess(token, ctx);
subscriber = context.msgSender;
userData = context.userData;
}
(
vars.iId,
vars.sId,
vars.idata,
,
vars.sdata
) = _loadAllData(token, publisher, subscriber, indexId, true);
// should not revoke an pending(un-approved) subscription
require(vars.sdata.subId != _UNALLOCATED_SUB_ID, "IDA: E_SUBS_NOT_APPROVED");
cbStates = AgreementLibrary.createCallbackInputs(
token,
publisher,
vars.sId,
"");
newCtx = ctx;
cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_TERMINATED_NOOP;
vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, newCtx);
int256 balanceDelta = int256(vars.idata.indexValue - vars.sdata.indexValue) * int256(vars.sdata.units);
vars.idata.totalUnitsApproved = vars.idata.totalUnitsApproved.sub(vars.sdata.units, "IDA: E_OVERFLOW");
vars.idata.totalUnitsPending = vars.idata.totalUnitsPending.add(vars.sdata.units, "IDA: E_OVERFLOW");
token.updateAgreementData(vars.iId, _encodeIndexData(vars.idata));
// remove subscription from subscriber's bitmap
_clearSubsBitmap(token, subscriber, vars.sdata.subId);
// sync pending distributions
vars.sdata.indexValue = vars.idata.indexValue;
// unlink publisher and subscriber
vars.sdata.subId = _UNALLOCATED_SUB_ID;
token.updateAgreementData(vars.sId, _encodeSubscriptionData(vars.sdata));
// settle subscriber static balance as a result to keep balance unchanged
token.settleBalance(subscriber, balanceDelta);
cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_TERMINATED_NOOP;
AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx);
emit IndexUnsubscribed(token, publisher, indexId, subscriber, userData);
emit SubscriptionRevoked(token, subscriber, publisher, indexId, userData);
}
/// @dev IInstantDistributionAgreementV1.updateSubscription implementation
function updateSubscription(
ISuperfluidToken token,
uint32 indexId,
address subscriber,
uint128 units,
bytes calldata ctx
)
external override
returns(bytes memory newCtx)
{
_SubscriptionOperationVars memory vars;
AgreementLibrary.CallbackInputs memory cbStates;
bytes memory userData;
address publisher;
{
ISuperfluid.Context memory context = AgreementLibrary.authorizeTokenAccess(token, ctx);
userData = context.userData;
publisher = context.msgSender;
}
(
vars.iId,
vars.sId,
vars.idata,
vars.subscriptionExists,
vars.sdata
) = _loadAllData(token, publisher, subscriber, indexId, false);
cbStates = AgreementLibrary.createCallbackInputs(
token,
subscriber,
vars.sId,
"");
newCtx = ctx;
// before-hook callback
if (vars.subscriptionExists) {
cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_UPDATED_NOOP;
vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, newCtx);
} else {
cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_CREATED_NOOP;
vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, newCtx);
}
// update publisher data
if (vars.subscriptionExists && vars.sdata.subId != _UNALLOCATED_SUB_ID) {
// if the subscription exist and not approved, update the approved units amount
// update total units
vars.idata.totalUnitsApproved = (
uint256(vars.idata.totalUnitsApproved) +
uint256(units) -
uint256(vars.sdata.units)
).toUint128();
token.updateAgreementData(vars.iId, _encodeIndexData(vars.idata));
} else if (vars.subscriptionExists) {
// if the subscription exists and approved, update the pending units amount
// update pending subscription units of the publisher
vars.idata.totalUnitsPending = (
uint256(vars.idata.totalUnitsPending) +
uint256(units) -
uint256(vars.sdata.units)
).toUint128();
token.updateAgreementData(vars.iId, _encodeIndexData(vars.idata));
} else {
// if the E_NO_SUBS, create it and then update the pending units amount
// create unallocated subscription
vars.sdata = SubscriptionData({
publisher: publisher,
indexId: indexId,
subId: _UNALLOCATED_SUB_ID,
units: units,
indexValue: vars.idata.indexValue
});
token.createAgreement(vars.sId, _encodeSubscriptionData(vars.sdata));
vars.idata.totalUnitsPending = vars.idata.totalUnitsPending.add(units, "IDA: E_OVERFLOW");
token.updateAgreementData(vars.iId, _encodeIndexData(vars.idata));
}
int256 balanceDelta = int256(vars.idata.indexValue - vars.sdata.indexValue) * int256(vars.sdata.units);
// adjust publisher's deposit and balances if subscription is pending
if (vars.sdata.subId == _UNALLOCATED_SUB_ID) {
_adjustPublisherDeposit(token, publisher, -balanceDelta);
token.settleBalance(publisher, -balanceDelta);
}
// settle subscriber static balance
token.settleBalance(subscriber, balanceDelta);
// update subscription data if necessary
if (vars.subscriptionExists) {
vars.sdata.indexValue = vars.idata.indexValue;
vars.sdata.units = units;
token.updateAgreementData(vars.sId, _encodeSubscriptionData(vars.sdata));
}
// after-hook callback
if (vars.subscriptionExists) {
cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_UPDATED_NOOP;
AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx);
} else {
cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_CREATED_NOOP;
AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx);
}
emit IndexUnitsUpdated(token, publisher, indexId, subscriber, units, userData);
emit SubscriptionUnitsUpdated(token, subscriber, publisher, indexId, units, userData);
}
/// @dev IInstantDistributionAgreementV1.getSubscription implementation
function getSubscription(
ISuperfluidToken token,
address publisher,
uint32 indexId,
address subscriber
)
external view override
returns (
bool exist,
bool approved,
uint128 units,
uint256 pendingDistribution
)
{
bytes32 iId;
bytes32 sId;
IndexData memory idata;
SubscriptionData memory sdata;
(
iId,
sId,
idata,
exist,
sdata
) = _loadAllData(token, publisher, subscriber, indexId, false);
if (!exist) return (false, false, 0, 0);
approved = sdata.subId != _UNALLOCATED_SUB_ID;
units = sdata.units;
pendingDistribution = approved ? 0 : uint256(idata.indexValue - sdata.indexValue) * uint256(sdata.units);
}
/// @dev IInstantDistributionAgreementV1.getSubscriptionByID implementation
function getSubscriptionByID(
ISuperfluidToken token,
bytes32 agreementId
)
external view override
returns(
address publisher,
uint32 indexId,
bool approved,
uint128 units,
uint256 pendingDistribution
)
{
bool exist;
bytes32 iId;
IndexData memory idata;
SubscriptionData memory sdata;
(exist, sdata) = _getSubscriptionData(token, agreementId);
require(exist, "IDA: E_NO_SUBS");
publisher = sdata.publisher;
indexId = sdata.indexId;
iId = _getPublisherId(publisher, indexId);
(exist, idata) = _getIndexData(token, iId);
assert(exist);
approved = sdata.subId != _UNALLOCATED_SUB_ID;
units = sdata.units;
pendingDistribution = approved ? 0 :
uint256(idata.indexValue - sdata.indexValue) * uint256(sdata.units);
}
/// @dev IInstantDistributionAgreementV1.listSubscriptions implementation
function listSubscriptions(
ISuperfluidToken token,
address subscriber
)
external view override
returns(
address[] memory publishers,
uint32[] memory indexIds,
uint128[] memory unitsList)
{
uint32[] memory slotIds;
bytes32[] memory sidList;
(slotIds, sidList) = _listSubscriptionIds(token, subscriber);
bool exist;
SubscriptionData memory sdata;
publishers = new address[](sidList.length);
indexIds = new uint32[](sidList.length);
unitsList = new uint128[](sidList.length);
for (uint32 i = 0; i < sidList.length; ++i) {
uint32 subId = slotIds[i];
bytes32 sId = sidList[i];
(exist, sdata) = _getSubscriptionData(token, sId);
assert(exist);
assert(sdata.subId == subId);
publishers[i] = sdata.publisher;
indexIds[i] = sdata.indexId;
unitsList[i] = sdata.units;
}
}
/// @dev IInstantDistributionAgreementV1.deleteSubscription implementation
function deleteSubscription(
ISuperfluidToken token,
address publisher,
uint32 indexId,
address subscriber,
bytes calldata ctx
)
external override
returns(bytes memory newCtx)
{
_SubscriptionOperationVars memory vars;
AgreementLibrary.CallbackInputs memory cbStates;
address sender;
bytes memory userData;
{
ISuperfluid.Context memory context = AgreementLibrary.authorizeTokenAccess(token, ctx);
sender = context.msgSender;
userData = context.userData;
}
// both publisher and subscriber can delete a subscription
require(sender == publisher, "IDA: E_NOT_ALLOWED");
(
vars.iId,
vars.sId,
vars.idata,
,
vars.sdata
) = _loadAllData(token, publisher, subscriber, indexId, true);
cbStates = AgreementLibrary.createCallbackInputs(
token,
sender == subscriber ? publisher : subscriber,
vars.sId,
"");
newCtx = ctx;
cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_TERMINATED_NOOP;
vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, newCtx);
int256 balanceDelta = int256(vars.idata.indexValue - vars.sdata.indexValue) * int256(vars.sdata.units);
// update publisher index agreement data
if (vars.sdata.subId != _UNALLOCATED_SUB_ID) {
vars.idata.totalUnitsApproved = vars.idata.totalUnitsApproved.sub(vars.sdata.units, "IDA: E_OVERFLOW");
} else {
vars.idata.totalUnitsPending = vars.idata.totalUnitsPending.sub(vars.sdata.units, "IDA: E_OVERFLOW");
}
token.updateAgreementData(vars.iId, _encodeIndexData(vars.idata));
// remove subscription from subscriber's bitmap
if (vars.sdata.subId != _UNALLOCATED_SUB_ID) {
_clearSubsBitmap(token, subscriber, vars.sdata.subId);
}
// move from publisher's deposit to static balance
if (vars.sdata.subId == _UNALLOCATED_SUB_ID) {
_adjustPublisherDeposit(token, publisher, -balanceDelta);
token.settleBalance(publisher, -balanceDelta);
}
// terminate subscription agreement data
token.terminateAgreement(vars.sId, 2);
// settle subscriber static balance
token.settleBalance(subscriber, balanceDelta);
cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_TERMINATED_NOOP;
AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx);
emit IndexUnsubscribed(token, publisher, indexId, subscriber, userData);
emit SubscriptionRevoked(token, subscriber, publisher, indexId, userData);
emit IndexUnitsUpdated(token, publisher, indexId, subscriber, 0, userData);
emit SubscriptionUnitsUpdated(token, subscriber, publisher, indexId, 0, userData);
}
function claim(
ISuperfluidToken token,
address publisher,
uint32 indexId,
address subscriber,
bytes calldata ctx
)
external override
returns(bytes memory newCtx)
{
_SubscriptionOperationVars memory vars;
AgreementLibrary.CallbackInputs memory cbStates;
(
vars.iId,
vars.sId,
vars.idata,
,
vars.sdata
) = _loadAllData(token, publisher, subscriber, indexId, true);
// required condition check
require(vars.sdata.subId == _UNALLOCATED_SUB_ID, "IDA: E_SUBS_APPROVED");
uint256 pendingDistribution = uint256(vars.idata.indexValue - vars.sdata.indexValue)
* uint256(vars.sdata.units);
cbStates = AgreementLibrary.createCallbackInputs(
token,
publisher,
vars.sId,
"");
newCtx = ctx;
if (pendingDistribution > 0) {
cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_UPDATED_NOOP;
vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, newCtx);
// adjust publisher's deposits
_adjustPublisherDeposit(token, publisher, -int256(pendingDistribution));
token.settleBalance(publisher, -int256(pendingDistribution));
// update subscription data and adjust subscriber's balance
vars.sdata.indexValue = vars.idata.indexValue;
token.updateAgreementData(vars.sId, _encodeSubscriptionData(vars.sdata));
token.settleBalance(subscriber, int256(pendingDistribution));
emit IndexDistributionClaimed(token, publisher, indexId, subscriber, pendingDistribution);
emit SubscriptionDistributionClaimed(token, subscriber, publisher, indexId, pendingDistribution);
cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_UPDATED_NOOP;
AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx);
} else {
// nothing to be recorded in this case
newCtx = ctx;
}
}
function _loadAllData(
ISuperfluidToken token,
address publisher,
address subscriber,
uint32 indexId,
bool requireSubscriptionExisting
)
private view
returns (
bytes32 iId,
bytes32 sId,
IndexData memory idata,
bool subscriptionExists,
SubscriptionData memory sdata
)
{
bool indexExists;
iId = _getPublisherId(publisher, indexId);
sId = _getSubscriptionId(subscriber, iId);
(indexExists, idata) = _getIndexData(token, iId);
require(indexExists, "IDA: E_NO_INDEX");
(subscriptionExists, sdata) = _getSubscriptionData(token, sId);
if (requireSubscriptionExisting) {
require(subscriptionExists, "IDA: E_NO_SUBS");
// sanity check
assert(sdata.publisher == publisher);
assert(sdata.indexId == indexId);
}
}
/**************************************************************************
* internal helpers
*************************************************************************/
function _getPublisherId(
address publisher,
uint32 indexId
)
private pure
returns (bytes32 iId)
{
return keccak256(abi.encodePacked("publisher", publisher, indexId));
}
function _getSubscriptionId(
address subscriber,
bytes32 iId
)
private pure
returns (bytes32 sId)
{
return keccak256(abi.encodePacked("subscription", subscriber, iId));
}
// # Index data operations
//
// Data packing:
//
// WORD 1: | existence bit | indexValue |
// | 128b | 128b |
// WORD 2: | totalUnitsPending | totalUnitsApproved |
// | 128b | 12b |
function _encodeIndexData(
IndexData memory idata
)
private pure
returns (bytes32[] memory data) {
data = new bytes32[](2);
data[0] = bytes32(
uint256(1 << 128) /* existance bit */ |
uint256(idata.indexValue)
);
data[1] = bytes32(
(uint256(idata.totalUnitsApproved)) |
(uint256(idata.totalUnitsPending) << 128)
);
}
function _hasIndexData(
ISuperfluidToken token,
bytes32 iId
)
private view
returns (bool exist)
{
bytes32[] memory adata = token.getAgreementData(address(this), iId, 2);
uint256 a = uint256(adata[0]);
exist = a > 0;
}
function _getIndexData(
ISuperfluidToken token,
bytes32 iId
)
private view
returns (bool exist, IndexData memory idata)
{
bytes32[] memory adata = token.getAgreementData(address(this), iId, 2);
uint256 a = uint256(adata[0]);
uint256 b = uint256(adata[1]);
exist = a > 0;
if (exist) {
idata.indexValue = uint128(a & uint256(int128(-1)));
idata.totalUnitsApproved = uint128(b & uint256(int128(-1)));
idata.totalUnitsPending = uint128(b >> 128);
}
}
// # Publisher's deposit amount
//
// It is stored in state slot in one word
function _getPublisherDeposit(
ISuperfluidToken token,
address publisher
)
private view
returns (uint256)
{
bytes32[] memory data = token.getAgreementStateSlot(
address(this),
publisher,
_PUBLISHER_DEPOSIT_STATE_SLOT_ID,
1);
return uint256(data[0]);
}
function _adjustPublisherDeposit(
ISuperfluidToken token,
address publisher,
int256 delta
)
private
{
if (delta == 0) return;
bytes32[] memory data = token.getAgreementStateSlot(
address(this),
publisher,
_PUBLISHER_DEPOSIT_STATE_SLOT_ID,
1);
data[0] = bytes32(int256(data[0]) + delta);
token.updateAgreementStateSlot(
publisher,
_PUBLISHER_DEPOSIT_STATE_SLOT_ID,
data);
}
// # Subscription data operations
//
// Data packing:
//
// WORD 1: | publisher | RESERVED | indexId | subId |
// | 160b | 32b | 32b | 32b |
// WORD 2: | units | indexValue |
// | 128b | 128b |
function _encodeSubscriptionData(
SubscriptionData memory sdata
)
private pure
returns (bytes32[] memory data)
{
data = new bytes32[](2);
data[0] = bytes32(
(uint256(sdata.publisher) << (12*8)) |
(uint256(sdata.indexId) << 32) |
uint256(sdata.subId)
);
data[1] = bytes32(
uint256(sdata.indexValue) |
(uint256(sdata.units) << 128)
);
}
function _getSubscriptionData(
ISuperfluidToken token,
bytes32 sId
)
private view
returns (bool exist, SubscriptionData memory sdata)
{
bytes32[] memory adata = token.getAgreementData(address(this), sId, 2);
uint256 a = uint256(adata[0]);
uint256 b = uint256(adata[1]);
exist = a > 0;