-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathFoundrySuperfluidTester.t.sol
More file actions
1826 lines (1578 loc) · 79 KB
/
FoundrySuperfluidTester.t.sol
File metadata and controls
1826 lines (1578 loc) · 79 KB
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: MIT
pragma solidity >=0.8.11;
import "forge-std/Test.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { ERC1820RegistryCompiled } from "../../contracts/libs/ERC1820RegistryCompiled.sol";
import { SuperfluidFrameworkDeployer } from "../../contracts/utils/SuperfluidFrameworkDeployer.t.sol";
import { Superfluid } from "../../contracts/superfluid/Superfluid.sol";
import { ISuperfluidPool, SuperfluidPool } from "../../contracts/agreements/gdav1/SuperfluidPool.sol";
import {
IGeneralDistributionAgreementV1,
PoolConfig,
PoolERC20Metadata
} from "../../contracts/interfaces/agreements/gdav1/IGeneralDistributionAgreementV1.sol";
import { IPoolNFTBase } from "../../contracts/interfaces/agreements/gdav1/IPoolNFTBase.sol";
import { IPoolAdminNFT } from "../../contracts/interfaces/agreements/gdav1/IPoolAdminNFT.sol";
import { IPoolMemberNFT } from "../../contracts/interfaces/agreements/gdav1/IPoolMemberNFT.sol";
import { ISuperfluidToken } from "../../contracts/interfaces/superfluid/ISuperfluidToken.sol";
import { ISETH } from "../../contracts/interfaces/tokens/ISETH.sol";
import { UUPSProxy } from "../../contracts/upgradability/UUPSProxy.sol";
import { ConstantFlowAgreementV1 } from "../../contracts/agreements/ConstantFlowAgreementV1.sol";
import { SuperTokenV1Library } from "../../contracts/apps/SuperTokenV1Library.sol";
import { IERC20, ISuperToken, SuperToken, IConstantOutflowNFT, IConstantInflowNFT }
from "../../contracts/superfluid/SuperToken.sol";
import { SuperfluidLoader } from "../../contracts/utils/SuperfluidLoader.sol";
import { TestResolver } from "../../contracts/utils/TestResolver.sol";
import { TestToken } from "../../contracts/utils/TestToken.sol";
/// @title FoundrySuperfluidTester
/// @dev A contract that can be inherited from to test Superfluid agreements
///
/// Types of SuperToken to test:
/// - (0) | WRAPPER_SUPER_TOKEN: has underlying ERC20 token (e.g. USDC)
/// - (1) | NATIVE_ASSET_SUPER_TOKEN: underlying asset is the native gas token (e.g. ETH)
/// - (2) | PURE_SUPER_TOKEN: has no underlying AND is purely a SuperToken
/// - (3) | CUSTOM_WRAPPER_SUPER_TOKEN: has underlying ERC20 token (e.g. USDC) AND has custom SuperToken logic
/// - (4) | CUSTOM_PURE_SUPER_TOKEN: has no underlying AND is purely a SuperToken AND has custom SuperToken logic
///
/// Definitions
/// - AUM: Assets Under Management
/// - Wrapper: underlyingToken.balanceOf(address(superToken))
/// - Native: address(superToken).balance
/// - Pure: superToken.totalSupply()
contract FoundrySuperfluidTester is Test {
using SuperTokenV1Library for ISuperToken;
using EnumerableSet for EnumerableSet.Bytes32Set;
using EnumerableSet for EnumerableSet.AddressSet;
using SafeCast for uint256;
using SafeCast for int256;
enum TestSuperTokenType {
WRAPPER_SUPER_TOKEN,
NATIVE_ASSET_SUPER_TOKEN,
PURE_SUPER_TOKEN,
CUSTOM_WRAPPER_SUPER_TOKEN,
CUSTOM_PURE_SUPER_TOKEN,
UNSUPPORTED_TOKEN_TYPE
}
struct _StackVars_UseBools {
bool useForwarder;
bool useGDA;
}
struct RealtimeBalance {
int256 availableBalance;
uint256 deposit;
uint256 owedDeposit;
uint256 timestamp;
}
struct IDASubscriptionParams {
ISuperToken superToken;
address publisher;
address subscriber;
uint32 indexId;
}
struct ExpectedSuperfluidPoolData {
int128 totalUnits;
int128 connectedUnits;
int128 disconnectedUnits;
int96 connectedFlowRate;
int96 disconnectedFlowRate;
int256 disconnectedBalance;
}
struct ExpectedPoolMemberData {
bool isConnected;
uint128 ownedUnits;
int96 flowRate;
int96 netFlowRate;
}
struct PoolUnitData {
uint128 totalUnits;
uint128 connectedUnits;
uint128 disconnectedUnits;
}
struct PoolFlowRateData {
int96 totalFlowRate;
int96 totalConnectedFlowRate;
int96 totalDisconnectedFlowRate;
}
error INVALID_TEST_SUPER_TOKEN_TYPE();
SuperfluidFrameworkDeployer internal immutable sfDeployer;
TestSuperTokenType internal immutable testSuperTokenType;
uint256 internal constant DEFAULT_WARP_TIME = 1 days;
uint256 internal constant INIT_TOKEN_BALANCE = type(uint128).max;
uint256 internal constant INIT_SUPER_TOKEN_BALANCE = type(uint88).max;
string internal constant DEFAULT_TEST_TOKEN_TYPE = "WRAPPER_SUPER_TOKEN";
string internal constant TOKEN_TYPE_ENV_KEY = "TOKEN_TYPE";
address internal constant admin = address(0x420);
address internal constant alice = address(0x421);
address internal constant bob = address(0x422);
address internal constant carol = address(0x423);
address internal constant dan = address(0x424);
address internal constant eve = address(0x425);
address internal constant frank = address(0x426);
address internal constant grace = address(0x427);
address internal constant heidi = address(0x428);
address internal constant ivan = address(0x429);
address[] internal TEST_ACCOUNTS = [admin, alice, bob, carol, dan, eve, frank, grace, heidi, ivan];
/// @dev Other account addresses added that aren't testers (pools, super apps, smart contracts)
EnumerableSet.AddressSet internal OTHER_ACCOUNTS;
uint256 internal immutable N_TESTERS;
SuperfluidFrameworkDeployer.Framework internal sf;
/// @dev The current underlying token being tested (applies only to wrapper super tokens)
TestToken internal token;
/// @dev The current super token being tested
ISuperToken internal superToken;
/// @dev The expected total supply of the current super token being tested
uint256 private _expectedTotalSupply;
/// @notice A mapping from super token to account to realtime balance data snapshot
/// @dev Used for validating that balances are correct
mapping(ISuperToken => mapping(address account => RealtimeBalance balanceSnapshot)) internal _balanceSnapshots;
/// @notice A mapping from super token to account to flowIDs of outflows from the account for the CFA
mapping(ISuperToken => mapping(address account => EnumerableSet.Bytes32Set flowIDs)) internal _outflows;
/// @notice A mapping from super token to account to flowIDs of inflows to the account for the CFA
mapping(ISuperToken => mapping(address account => EnumerableSet.Bytes32Set flowIDs)) internal _inflows;
/// @notice A mapping from super token to account to indexIDs of indexes of the account for the IDA
mapping(ISuperToken => mapping(address account => EnumerableSet.Bytes32Set indexIDs)) internal _indexIDs;
/// @notice A mapping from super token to subId to sub.indexValue for the IDA
mapping(ISuperToken => mapping(bytes32 subId => uint128 indexValue)) internal _lastUpdatedSubIndexValues;
/// @notice A mapping from pool to
mapping(address pool => EnumerableSet.AddressSet members) internal _poolMembers;
mapping(address pool => mapping(address member => ExpectedPoolMemberData expectedData)) internal
_poolToExpectedMemberData;
/// @notice The default poolConfig (true, true)
PoolConfig public poolConfig;
constructor(uint8 nTesters) {
// deploy ERC1820 registry
vm.etch(ERC1820RegistryCompiled.at, ERC1820RegistryCompiled.bin);
// deploy SuperfluidFrameworkDeployer
// which deploys in its constructor:
// - TestGovernance
// - Host
// - CFA
// - IDA
// - SuperToken logic
// - SuperTokenFactory
// - Resolver
// - SuperfluidLoader
// - CFAv1Forwarder
sfDeployer = new SuperfluidFrameworkDeployer();
sfDeployer.deployTestFramework();
sf = sfDeployer.getFramework();
require(nTesters <= TEST_ACCOUNTS.length, "too many testers");
N_TESTERS = nTesters;
_addAccount(address(sf.gda));
// Set the token type being tested
string memory tokenType = vm.envOr(TOKEN_TYPE_ENV_KEY, DEFAULT_TEST_TOKEN_TYPE);
bytes32 hashedTokenType = keccak256(abi.encode(tokenType));
_addAccount(address(sf.toga));
poolConfig = PoolConfig({ transferabilityForUnitsOwner: true, distributionFromAnyAddress: true });
// @note we must use a ternary expression because immutable variables cannot be initialized
// in an if statement
testSuperTokenType = hashedTokenType == keccak256(abi.encode("WRAPPER_SUPER_TOKEN"))
? TestSuperTokenType.WRAPPER_SUPER_TOKEN
: hashedTokenType == keccak256(abi.encode("NATIVE_ASSET_SUPER_TOKEN"))
? TestSuperTokenType.NATIVE_ASSET_SUPER_TOKEN
: hashedTokenType == keccak256(abi.encode("PURE_SUPER_TOKEN"))
? TestSuperTokenType.PURE_SUPER_TOKEN
: hashedTokenType == keccak256(abi.encode("CUSTOM_WRAPPER_SUPER_TOKEN"))
? TestSuperTokenType.CUSTOM_WRAPPER_SUPER_TOKEN
: hashedTokenType == keccak256(abi.encode("CUSTOM_PURE_SUPER_TOKEN"))
? TestSuperTokenType.CUSTOM_PURE_SUPER_TOKEN
: TestSuperTokenType.UNSUPPORTED_TOKEN_TYPE;
if (testSuperTokenType == TestSuperTokenType.UNSUPPORTED_TOKEN_TYPE) revert INVALID_TEST_SUPER_TOKEN_TYPE();
}
/*//////////////////////////////////////////////////////////////////////////
Test Setup/Harness
//////////////////////////////////////////////////////////////////////////*/
function setUp() public virtual {
_setUpSuperToken();
}
/// @notice Deploys a Wrapper SuperToken with an underlying test token and gives tokens to the test accounts
function _setUpWrapperSuperToken() internal {
(token, superToken) = sfDeployer.deployWrapperSuperToken("FTT", "FTT", 18, type(uint256).max, address(0));
address[] memory accounts = _listAccounts();
for (uint256 i = 0; i < accounts.length; ++i) {
address account = accounts[i];
token.mint(account, INIT_TOKEN_BALANCE);
vm.startPrank(account);
token.approve(address(superToken), INIT_SUPER_TOKEN_BALANCE);
superToken.upgrade(INIT_SUPER_TOKEN_BALANCE);
_expectedTotalSupply += INIT_SUPER_TOKEN_BALANCE;
vm.stopPrank();
_helperTakeBalanceSnapshot(superToken, account);
}
}
/// @notice Deploys a Native Asset SuperToken and gives tokens to the test accounts
/// @dev We use vm.deal to give each account a starting amount of ether
function _setUpNativeAssetSuperToken() internal {
(superToken) = sfDeployer.deployNativeAssetSuperToken("Super ETH", "ETHx");
address[] memory accounts = _listAccounts();
for (uint256 i = 0; i < accounts.length; ++i) {
address account = accounts[i];
vm.startPrank(account);
vm.deal(account, INIT_TOKEN_BALANCE);
ISETH(address(superToken)).upgradeByETH{ value: INIT_SUPER_TOKEN_BALANCE }();
_expectedTotalSupply += INIT_SUPER_TOKEN_BALANCE;
vm.stopPrank();
_helperTakeBalanceSnapshot(superToken, account);
}
}
/// @notice Deploys a Pure SuperToken and gives tokens to the test accounts
/// @dev This contract receives the total supply then doles it out to the test accounts
function _setUpPureSuperToken() internal {
address[] memory accounts = _listAccounts();
uint256 initialSupply = INIT_SUPER_TOKEN_BALANCE * accounts.length;
(superToken) = sfDeployer.deployPureSuperToken("Super MR", "MRx", initialSupply);
_expectedTotalSupply = initialSupply;
for (uint256 i = 0; i < accounts.length; ++i) {
address account = accounts[i];
superToken.transfer(account, INIT_SUPER_TOKEN_BALANCE);
_helperTakeBalanceSnapshot(superToken, account);
}
}
/// @notice Deploys a SuperToken based on the testSuperTokenType selected
function _setUpSuperToken() internal {
if (testSuperTokenType == TestSuperTokenType.WRAPPER_SUPER_TOKEN) {
_setUpWrapperSuperToken();
} else if (testSuperTokenType == TestSuperTokenType.NATIVE_ASSET_SUPER_TOKEN) {
_setUpNativeAssetSuperToken();
} else if (testSuperTokenType == TestSuperTokenType.PURE_SUPER_TOKEN) {
_setUpPureSuperToken();
// @note TODO these still have to be implemented
} else if (testSuperTokenType == TestSuperTokenType.CUSTOM_WRAPPER_SUPER_TOKEN) {
// _setUpCustomWrapperSuperToken();
} else if (testSuperTokenType == TestSuperTokenType.CUSTOM_PURE_SUPER_TOKEN) {
// _setUpCustomPureSuperToken();
} else {
revert("invalid test token type");
}
}
/// @notice Adds an account to the testing mix
function _addAccount(address account) internal {
if (OTHER_ACCOUNTS.contains(account)) return;
for (uint i = 0; i < TEST_ACCOUNTS.length; ++i) {
if (TEST_ACCOUNTS[i] == account) return;
}
OTHER_ACCOUNTS.add(account);
}
function _listAccounts() internal view returns (address[] memory accounts) {
accounts = new address[](N_TESTERS + OTHER_ACCOUNTS.values().length);
for (uint i = 0; i < N_TESTERS; ++i) {
accounts[i] = address(TEST_ACCOUNTS[i]);
}
for (uint i = 0; i < OTHER_ACCOUNTS.values().length; ++i) {
accounts[i + N_TESTERS] = OTHER_ACCOUNTS.values()[i];
}
}
/*//////////////////////////////////////////////////////////////////////////
Invariant Definitions
//////////////////////////////////////////////////////////////////////////*/
/// @notice Liquidity Sum Invariant definition
/// @dev Liquidity Sum Invariant: Expected Total Supply === Liquidity Sum
/// Liquidity Sum = sum of available balance, deposit and owed deposit for all users
/// @return bool Liquidity Sum Invariant holds true
function _definitionLiquiditySumInvariant() internal view returns (bool) {
int256 liquiditySum = _helperGetSuperTokenLiquiditySum(superToken);
return int256(_expectedTotalSupply) == liquiditySum;
}
/// @notice AUM-RTB Accounting Invariant
/// @dev AUM-RTB Accounting Invariant: AUM >= RTB Sum
/// This invariant ensures that the RTB accounting is correct.
/// @return bool AUM-RTB Accounting Invariant holds true
function _definitionAumGtEqRtbSumInvariant() internal view returns (bool) {
uint256 aum = _helperGetSuperTokenAum(superToken);
int256 rtbSum = _helperGetSuperTokenLiquiditySum(superToken);
return aum >= uint256(rtbSum);
}
/// @notice Protocol Solvency Invariant definition
/// @dev Protocol Solvency Invariant: AUM >= Total Supply
/// This invariant ensures that if all users want to downgrade their SuperToken, they can
/// @return bool Protocol Solvency Invariant holds true
function _defintionAumGtEqSuperTokenTotalSupplyInvariant() internal view returns (bool) {
uint256 aum = _helperGetSuperTokenAum(superToken);
uint256 totalSupply = superToken.totalSupply();
return aum >= totalSupply;
}
/// @notice Net Flow Rate Sum Invariant definition
/// @dev Net Flow Rate Sum Invariant: Sum of all net flow rates === 0
/// @return bool Net Flow Rate Sum Invariant holds true
function _definitionNetFlowRateSumInvariant() internal view returns (bool) {
int96 netFlowRateSum = _helperGetNetFlowRateSum(superToken);
return netFlowRateSum == 0;
}
/// @notice Asserts that the global invariants hold true
function _assertGlobalInvariants() internal virtual {
_assertInvariantLiquiditySum();
_assertInvariantNetFlowRateSum();
_assertInvariantAumGtEqRtbSum();
_assertInvariantAumGtEqSuperTokenTotalSupply();
}
function _assertInvariantLiquiditySum() internal view {
assertTrue(_definitionLiquiditySumInvariant(), "Invariant: Liquidity Sum Invariant");
}
function _assertInvariantNetFlowRateSum() internal view {
assertTrue(_definitionNetFlowRateSumInvariant(), "Invariant: Net Flow Rate Sum Invariant");
}
function _assertInvariantAumGtEqRtbSum() internal view {
assertTrue(_definitionAumGtEqRtbSumInvariant(), "Invariant: AUM > RTB Sum");
}
function _assertInvariantAumGtEqSuperTokenTotalSupply() internal view {
assertTrue(_defintionAumGtEqSuperTokenTotalSupplyInvariant(), "Invariant: AUM > SuperToken Total Supply");
}
/// @notice Asserts that the real time balances for all active test accounts are expected
/// @dev We also take a balance snapshot after each assertion
/// @param superToken_ The SuperToken to check
function _assertRealTimeBalances(ISuperToken superToken_) internal {
address[] memory accounts = _listAccounts();
for (uint i; i < accounts.length; ++i) {
address account = accounts[i];
RealtimeBalance memory balanceSnapshot = _balanceSnapshots[superToken_][account];
(int256 avb, uint256 deposit, uint256 owedDeposit, uint256 currentTime) =
superToken_.realtimeBalanceOfNow(account);
int96 cfaNetFlowRate = superToken_.getCFANetFlowRate(account);
// GDA Net Flow Rate is 0 for pools because this is not accounted for in the pools' RTB
// however it is the disconnected flow rate for that pool
int96 gdaNetFlowRate =
sf.gda.isPool(superToken_, account) ? int96(0) : superToken_.getGDANetFlowRate(account);
int96 netFlowRate = cfaNetFlowRate + gdaNetFlowRate;
int256 amountFlowedSinceSnapshot = (currentTime - balanceSnapshot.timestamp).toInt256() * netFlowRate;
int256 expectedAvb = balanceSnapshot.availableBalance + amountFlowedSinceSnapshot;
assertEq(balanceSnapshot.deposit, deposit, "Real Time Balances: deposit");
assertEq(balanceSnapshot.owedDeposit, owedDeposit, "Real Time Balances: owed deposit");
assertEq(avb, expectedAvb, "Real Time Balances: available balance");
_helperTakeBalanceSnapshot(superToken_, account);
}
}
/// @notice Warps forwards 1 day and asserts balances of all testers and global invariants
function _warpAndAssertAll(ISuperToken superToken_) internal virtual {
vm.warp(block.timestamp + DEFAULT_WARP_TIME);
_assertRealTimeBalances(superToken_);
_assertGlobalInvariants();
}
/// @notice Warps forwards `time` seconds and asserts balances of all testers and global invariants
function _warpAndAssertAll(ISuperToken superToken_, uint256 time) internal virtual {
vm.warp(block.timestamp + time);
_assertRealTimeBalances(superToken_);
_assertGlobalInvariants();
}
/*//////////////////////////////////////////////////////////////////////////
Assume Helpers
//////////////////////////////////////////////////////////////////////////*/
/// @notice Assume a valid flow rate
/// @dev Flow rate must be greater than 0 and less than or equal to int32.max
function _assumeValidFlowRate(int96 desiredFlowRate) internal pure returns (int96 flowRate) {
vm.assume(desiredFlowRate > 0);
vm.assume(desiredFlowRate <= int96(uint96(uint256(type(uint64).max))));
flowRate = desiredFlowRate;
}
/*//////////////////////////////////////////////////////////////////////////
Helper Functions
//////////////////////////////////////////////////////////////////////////*/
// Getter Helpers
/// @notice Gets the AUM for a SuperToken
/// @dev This is dependent on the testSuperTokenType selected
/// @param superToken_ The SuperToken to get the AUM for
/// @return uint256 The AUM for the SuperToken
function _helperGetSuperTokenAum(ISuperToken superToken_) internal view returns (uint256) {
if (testSuperTokenType == TestSuperTokenType.WRAPPER_SUPER_TOKEN) {
return _helperGetWrapperSuperTokenAUM(superToken_);
} else if (testSuperTokenType == TestSuperTokenType.NATIVE_ASSET_SUPER_TOKEN) {
return _helperGetNativeAssetSuperTokenAUM(superToken_);
} else if (testSuperTokenType == TestSuperTokenType.PURE_SUPER_TOKEN) {
return _helperGetPureSuperTokenAUM(superToken_);
} else {
return 0;
}
}
/// @notice Gets the AUM for Wrapper SuperToken's
/// @param superToken_ The SuperToken to get the AUM for
/// @return uint256 The AUM for the SuperToken
function _helperGetWrapperSuperTokenAUM(ISuperToken superToken_) internal view returns (uint256) {
return ISuperToken(superToken_.getUnderlyingToken()).balanceOf(address(superToken_));
}
/// @notice Gets the AUM for Native Asset SuperToken's
/// @param superToken_ The SuperToken to get the AUM for
/// @return uint256 The AUM for the SuperToken
function _helperGetNativeAssetSuperTokenAUM(ISuperToken superToken_) internal view returns (uint256) {
return address(superToken_).balance;
}
/// @notice Gets the AUM for Pure SuperToken's
/// @param superToken_ The SuperToken to get the AUM for
/// @return uint256 The AUM for the SuperToken
function _helperGetPureSuperTokenAUM(ISuperToken superToken_) internal view returns (uint256) {
return superToken_.totalSupply();
}
/// @notice Gets the liquidity sum for a SuperToken
/// @param superToken_ The SuperToken to get the liquidity sum for
/// @return liquiditySum The liquidity sum for the SuperToken
function _helperGetSuperTokenLiquiditySum(ISuperToken superToken_) internal view returns (int256 liquiditySum) {
address[] memory accounts = _listAccounts();
for (uint256 i = 0; i < accounts.length; ++i) {
(int256 availableBalance, uint256 deposit, uint256 owedDeposit,) =
superToken_.realtimeBalanceOfNow(accounts[i]);
// FIXME: correct formula
// liquiditySum += availableBalance + int256(deposit) - int256(owedDeposit);
// current faulty one
liquiditySum +=
availableBalance + (deposit > owedDeposit ? int256(deposit) - int256(owedDeposit) : int256(0));
}
}
/// @notice Gets the net flow rate sum for a SuperToken
/// @dev This is the sum of net flow rates of the test accounts
/// @param superToken_ The SuperToken to get the net flow rate sum for
/// @return netFlowRateSum The net flow rate sum for the SuperToken
function _helperGetNetFlowRateSum(ISuperToken superToken_) internal view returns (int96 netFlowRateSum) {
address[] memory accounts = _listAccounts();
for (uint256 i = 0; i < accounts.length; ++i) {
netFlowRateSum += superToken_.getNetFlowRate(accounts[i]);
}
}
/// @notice Tries to get an IDA subscription
/// @dev This is needed in tests because it reverts if the subscriptio does not exist
/// @param superToken_ The SuperToken to get the subscription for
/// @param subId The ID of the subscription to get
/// @return approved Whether the subscription exists
/// @return units The units of the subscription
/// @return pendingDistribution The pending distribution of the subscription
function _helperTryGetSubscription(ISuperToken superToken_, bytes32 subId)
internal
view
returns (bool approved, uint128 units, uint256 pendingDistribution)
{
try sf.ida.getSubscriptionByID(superToken_, subId) returns (
address, uint32, bool isApproved, uint128 subUnits, uint256 pending
) {
approved = isApproved;
units = subUnits;
pendingDistribution = pending;
} catch { }
}
/// @notice Gets flow info and account flow info for a sender and receiver
/// @param superToken_ The SuperToken to get the flow info for
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
/// @return flowInfo The flow info between a sender-receiver
/// @return senderFlowInfo The account flow info for a sender
/// @return receiverFlowInfo The account flow info for a receiver
function _helperGetAllFlowInfo(ISuperToken superToken_, address sender, address receiver)
internal
view
returns (
ConstantFlowAgreementV1.FlowData memory flowInfo,
ConstantFlowAgreementV1.FlowData memory senderFlowInfo,
ConstantFlowAgreementV1.FlowData memory receiverFlowInfo
)
{
flowInfo = _helperGetFlowInfo(superToken_, sender, receiver);
senderFlowInfo = _helperGetAccountFlowInfo(superToken_, sender);
receiverFlowInfo = _helperGetAccountFlowInfo(superToken_, receiver);
}
/// @notice Gets flow info for a sender and receiver
/// @param superToken_ The SuperToken to get the flow info for
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
/// @return flowInfo The flow info between a sender-receiver
function _helperGetFlowInfo(ISuperToken superToken_, address sender, address receiver)
internal
view
returns (ConstantFlowAgreementV1.FlowData memory flowInfo)
{
(uint256 timestamp, int96 flowRate, uint256 deposit, uint256 owedDeposit) =
superToken_.getFlowInfo(sender, receiver);
flowInfo = ConstantFlowAgreementV1.FlowData(timestamp, flowRate, deposit, owedDeposit);
}
/// @notice Gets account flow info for an account
/// @param superToken_ The SuperToken to get the account flow info for
/// @param account The account to get the account flow info for
/// @return flowInfo The account flow info for an account
function _helperGetAccountFlowInfo(ISuperToken superToken_, address account)
internal
view
returns (ConstantFlowAgreementV1.FlowData memory flowInfo)
{
(uint256 timestamp, int96 flowRate, uint256 deposit, uint256 owedDeposit) =
sf.cfa.getAccountFlowInfo(superToken_, account);
flowInfo = ConstantFlowAgreementV1.FlowData(timestamp, flowRate, deposit, owedDeposit);
}
// Time Warp Helpers
/// @notice Warps to a timestamp where account is critical
/// @param superToken_ The SuperToken
/// @param account The account whose balance we want to "drain"
/// @param secondsCritical The number of seconds to warp to after the account is critical
function _helperWarpToCritical(ISuperToken superToken_, address account, uint256 secondsCritical) internal {
int96 netFlowRate = superToken_.getNetFlowRate(account);
assertTrue(netFlowRate < 0, "_helperWarpToCritical: netFlowRate must be less than 0 to reach critical");
assertTrue(secondsCritical > 0, "_helperWarpToCritical: secondsCritical must be > 0 to reach critical");
(int256 ab,,) = superToken_.realtimeBalanceOf(account, block.timestamp);
int256 timeToZero = ab / netFlowRate < 0 ? (ab / netFlowRate) * -1 : ab / netFlowRate;
uint256 amountToWarp = timeToZero.toUint256() + secondsCritical;
vm.warp(block.timestamp + amountToWarp);
assertTrue(superToken_.isAccountCriticalNow(account), "_helperWarpToCritical: account is not critical");
}
/// @notice Warps to a timestamp where account is insolvent
/// @param superToken_ The SuperToken
/// @param account The account whose balance we want to "drain"
/// @param liquidationPeriod The liquidation period of the SuperToken
/// @param secondsInsolvent The number of seconds to warp to after the account is insolvent
function _helperWarpToInsolvency(
ISuperToken superToken_,
address account,
uint256 liquidationPeriod,
uint256 secondsInsolvent
) internal {
int96 netFlowRate = superToken_.getNetFlowRate(account);
assertTrue(netFlowRate < 0, "_helperWarpToCritical: netFlowRate must be less than 0 to reach critical");
assertTrue(secondsInsolvent > 0, "_helperWarpToInsolvency: secondsInsolvent must be > 0 to reach insolvency");
(int256 ab,,) = superToken_.realtimeBalanceOf(account, block.timestamp);
int256 timeToZero = ab / netFlowRate < 0 ? (ab / netFlowRate) * -1 : ab / netFlowRate;
uint256 amountToWarp = timeToZero.toUint256() + liquidationPeriod + secondsInsolvent;
vm.warp(block.timestamp + amountToWarp);
assertFalse(superToken_.isAccountSolventNow(account), "_helperWarpToInsolvency: account is still solvent");
}
// ID generator helpers
/// @notice Generates a flow ID for a sender-receiver
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
/// @return id The flow ID for a sender-receiver
function _generateFlowId(address sender, address receiver) private pure returns (bytes32 id) {
return keccak256(abi.encode(sender, receiver));
}
/// @notice Generates a flowOperator ID for a sender-flowOperator
/// @param sender The sender of the flow
/// @param flowOperator The flowOperator of the flow
/// @return id The flowOperator ID for a sender-flowOperator
function _generateFlowOperatorId(address sender, address flowOperator) private pure returns (bytes32 id) {
return keccak256(abi.encode("flowOperator", sender, flowOperator));
}
/// @notice Generates a publisher ID for a publisher-indexId
/// @param publisher The publisher of the index
/// @param indexId The indexId of the index
/// @return iId The publisher ID for a publisher-indexId
function _generatePublisherId(address publisher, uint32 indexId) private pure returns (bytes32 iId) {
return keccak256(abi.encodePacked("publisher", publisher, indexId));
}
/// @notice Generates a subscription ID for a subscriber-publisherId
/// @param subscriber The subscriber of the index
/// @param iId The publisherId of the index
/// @return sId The subscription ID for a subscriber-publisherId
function _generateSubscriptionId(address subscriber, bytes32 iId) private pure returns (bytes32 sId) {
return keccak256(abi.encodePacked("subscription", subscriber, iId));
}
// Write Helpers
// Write Helpers - Testing State Changes
/// @notice Takes a RTB snapshot of a SuperToken for an account
/// @dev This must be called in the tests where a function is caled which settles balances in the protocol
/// @param superToken_ The SuperToken to take the RTB snapshot for
/// @param account The account to take the RTB snapshot for
function _helperTakeBalanceSnapshot(ISuperToken superToken_, address account) internal {
(int256 avb, uint256 deposit, uint256 owedDeposit, uint256 time) = superToken_.realtimeBalanceOfNow(account);
RealtimeBalance memory balanceSnapshot = RealtimeBalance(avb, deposit, owedDeposit, time);
_balanceSnapshots[superToken_][account] = balanceSnapshot;
}
/// @notice Adds inflows and outflows to the test state
/// @dev This must be called whenever a flow is created
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
function _helperAddInflowsAndOutflowsToTestState(address sender, address receiver) internal {
bytes32 flowId = _generateFlowId(sender, receiver);
EnumerableSet.Bytes32Set storage outflows = _outflows[superToken][sender];
if (!outflows.contains(flowId)) {
outflows.add(flowId);
}
EnumerableSet.Bytes32Set storage inflows = _inflows[superToken][receiver];
if (!inflows.contains(flowId)) {
inflows.add(flowId);
}
}
/// @notice Removes inflows and outflows from the test state
/// @dev This must be called whenever a flow is deleted
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
function _helperRemoveInflowsAndOutflowsFromTestState(address sender, address receiver) internal {
bytes32 flowId = _generateFlowId(sender, receiver);
EnumerableSet.Bytes32Set storage outflows = _outflows[superToken][sender];
if (outflows.contains(flowId)) {
outflows.remove(flowId);
}
EnumerableSet.Bytes32Set storage inflows = _inflows[superToken][receiver];
if (inflows.contains(flowId)) {
inflows.remove(flowId);
}
}
// Write Helpers - SuperToken
function _helperTransferAll(ISuperToken superToken_, address sender, address receiver) internal {
vm.startPrank(sender);
superToken_.transferAll(receiver);
vm.stopPrank();
_helperTakeBalanceSnapshot(superToken_, sender);
_helperTakeBalanceSnapshot(superToken_, receiver);
}
function _helperDeploySuperTokenAndInitialize(
ISuperToken previousSuperToken,
IERC20 underlyingToken,
uint8 underlyingDecimals,
string memory name,
string memory symbol,
address _admin
) internal returns (SuperToken localSuperToken) {
localSuperToken = new SuperToken(
sf.host,
IConstantOutflowNFT(address(0)),
IConstantInflowNFT(address(0)),
previousSuperToken.POOL_ADMIN_NFT(),
previousSuperToken.POOL_MEMBER_NFT()
);
localSuperToken.initializeWithAdmin(underlyingToken, underlyingDecimals, name, symbol, _admin);
}
// Write Helpers - ConstantFlowAgreementV1
/// @notice Creates a flow between a sender and receiver at a given flow rate
/// @dev This helper assumes a valid flow rate with vm.assume and asserts that state has updated as expected.
/// We assert:
/// - The flow info is properly set (flow rate, updated, deposit and owedDeposit are set as expected)
/// - The account flow info has been updated as expected for sender and receiver (delta applied to net flow rates +
/// deposit for sender)
/// - The balance of all test accounts has been updated as expected (balanceSnapshot + streamedAmountSince)
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
/// @param flowRate The desired flow rate
function _helperCreateFlow(ISuperToken superToken_, address sender, address receiver, int96 flowRate) internal {
flowRate = _assumeValidFlowRate(flowRate);
// Get Flow Data Before
(
ConstantFlowAgreementV1.FlowData memory flowInfoBefore,
ConstantFlowAgreementV1.FlowData memory senderFlowInfoBefore,
ConstantFlowAgreementV1.FlowData memory receiverFlowInfoBefore
) = _helperGetAllFlowInfo(superToken_, sender, receiver);
// Execute Create Flow
vm.startPrank(sender);
superToken_.createFlow(receiver, flowRate);
vm.stopPrank();
// Update Test State
{
_helperAddInflowsAndOutflowsToTestState(sender, receiver);
_helperTakeBalanceSnapshot(superToken_, sender);
_helperTakeBalanceSnapshot(superToken_, receiver);
}
// Assert Flow Data + Account Flow Info for sender/receiver
{
int96 flowRateDelta = flowRate - flowInfoBefore.flowRate;
_assertFlowData(superToken_, sender, receiver, flowRate, block.timestamp, 0);
_assertAccountFlowInfo(sender, flowRateDelta, senderFlowInfoBefore, true);
_assertAccountFlowInfo(receiver, flowRateDelta, receiverFlowInfoBefore, false);
}
// Assert RTB for all users
_assertRealTimeBalances(superToken_);
_assertGlobalInvariants();
}
/// @notice Updates a flow between a sender and receiver at a given flow rate
/// @dev This helper assumes a valid flow rate with vm.assume and asserts that state has updated as expected.
/// We assert:
/// - The flow info is properly set (flow rate, updated, deposit and owedDeposit are set as expected)
/// - The account flow info has been updated as expected for sender and receiver (delta applied to net flow rates +
/// deposit for sender)
/// - The balance of all test accounts has been updated as expected (balanceSnapshot + streamedAmountSince)
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
/// @param flowRate The desired flow rate
function _helperUpdateFlow(ISuperToken superToken_, address sender, address receiver, int96 flowRate) internal {
flowRate = _assumeValidFlowRate(flowRate);
// Get Flow Data Before
(
ConstantFlowAgreementV1.FlowData memory flowInfoBefore,
ConstantFlowAgreementV1.FlowData memory senderFlowInfoBefore,
ConstantFlowAgreementV1.FlowData memory receiverFlowInfoBefore
) = _helperGetAllFlowInfo(superToken_, sender, receiver);
// Execute Update Flow
vm.startPrank(sender);
superToken_.updateFlow(receiver, flowRate);
vm.stopPrank();
// Update Test State
{
_helperTakeBalanceSnapshot(superToken_, sender);
_helperTakeBalanceSnapshot(superToken_, receiver);
}
// Assert Flow Data + Account Flow Info for sender/receiver
{
int96 flowRateDelta = flowRate - flowInfoBefore.flowRate;
_assertFlowData(superToken_, sender, receiver, flowRate, block.timestamp, 0);
_assertAccountFlowInfo(sender, flowRateDelta, senderFlowInfoBefore, true);
_assertAccountFlowInfo(receiver, flowRateDelta, receiverFlowInfoBefore, false);
}
// Assert RTB for all users
_assertRealTimeBalances(superToken_);
_assertGlobalInvariants();
}
/// @notice Deletes a flow between a sender and receiver
/// @dev This helper assumes a valid flow rate with vm.assume and asserts that state has updated as expected.
/// We assert:
/// - The flow info is properly set (flow rate, updated, deposit and owedDeposit are set as expected)
/// - The account flow info has been updated as expected for sender and receiver (delta applied to net flow rates +
/// deposit for sender)
/// - The balance of all test accounts has been updated as expected (balanceSnapshot + streamedAmountSince)
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
function _helperDeleteFlow(ISuperToken superToken_, address caller, address sender, address receiver) internal {
// Get Flow Data Before
(
ConstantFlowAgreementV1.FlowData memory flowInfoBefore,
ConstantFlowAgreementV1.FlowData memory senderFlowInfoBefore,
ConstantFlowAgreementV1.FlowData memory receiverFlowInfoBefore
) = _helperGetAllFlowInfo(superToken_, sender, receiver);
// Execute Delete Flow
vm.startPrank(caller);
superToken_.deleteFlow(sender, receiver);
vm.stopPrank();
// Update Test State
{
_helperRemoveInflowsAndOutflowsFromTestState(sender, receiver);
_helperTakeBalanceSnapshot(superToken_, sender);
_helperTakeBalanceSnapshot(superToken_, receiver);
if (caller != sender && caller != receiver) {
_helperTakeBalanceSnapshot(superToken_, caller);
}
// Get the default reward address for the token and update their snapshot too in the
// liquidation case
address rewardAddress = sf.governance.getRewardAddress(sf.host, superToken_);
_helperTakeBalanceSnapshot(superToken_, rewardAddress);
}
// Assert Flow Data + Account Flow Info for sender/receiver
{
int96 flowRateDelta = -flowInfoBefore.flowRate;
_assertFlowDataIsEmpty(superToken_, sender, receiver);
_assertAccountFlowInfo(sender, flowRateDelta, senderFlowInfoBefore, true);
_assertAccountFlowInfo(receiver, flowRateDelta, receiverFlowInfoBefore, false);
}
// Assert RTB for all users
_assertRealTimeBalances(superToken_);
_assertGlobalInvariants();
}
/// @notice Creates an ACL flow by the opeartor between a sender and receiver at a given flow rate
/// @dev This helper assumes a valid flow rate with vm.assume and asserts that state has updated as expected.
/// We assert:
/// - The flow info is properly set (flow rate, updated, deposit and owedDeposit are set as expected)
/// - The account flow info has been updated as expected for sender and receiver (delta applied to net flow rates +
/// deposit for sender)
/// - The balance of all test accounts has been updated as expected (balanceSnapshot + streamedAmountSince)
/// - The flow rate allowance has been deducted accordingly (only if not max allowancea)
/// @param operator The flow operator
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
/// @param flowRate The desired flow rate
function _helperCreateFlowFrom(
ISuperToken superToken_,
address operator,
address sender,
address receiver,
int96 flowRate
) internal {
flowRate = _assumeValidFlowRate(flowRate);
// Get Flow Data Before
(
ConstantFlowAgreementV1.FlowData memory flowInfoBefore,
ConstantFlowAgreementV1.FlowData memory senderFlowInfoBefore,
ConstantFlowAgreementV1.FlowData memory receiverFlowInfoBefore
) = _helperGetAllFlowInfo(superToken, sender, receiver);
// Get Flow Operator Data Before
(,,, int96 flowRateAllowanceBefore) = superToken_.getFlowPermissions(sender, operator);
// Execute Create Flow as FlowOperator
vm.startPrank(operator);
superToken_.createFlowFrom(sender, receiver, flowRate);
vm.stopPrank();
// Update Test State
{
_helperAddInflowsAndOutflowsToTestState(sender, receiver);
_helperTakeBalanceSnapshot(superToken, sender);
_helperTakeBalanceSnapshot(superToken, receiver);
}
// Assert Flow Data + Account Flow Info for sender/receiver
int96 flowRateDelta = flowRate - flowInfoBefore.flowRate;
{
_assertFlowData(superToken_, sender, receiver, flowRate, block.timestamp, 0);
_assertAccountFlowInfo(sender, flowRateDelta, senderFlowInfoBefore, true);
_assertAccountFlowInfo(receiver, flowRateDelta, receiverFlowInfoBefore, false);
}
// Assert FlowOperator Data
{
(,,, int96 flowRateAllowanceAfter) = superToken_.getFlowPermissions(sender, operator);
if (flowRateAllowanceBefore == type(int96).max) {
assertEq(flowRateAllowanceAfter, flowRateAllowanceBefore, "CreateFlowFrom: Max flow allowance deducted");
} else {
assertEq(
flowRateAllowanceAfter,
flowRateAllowanceBefore - flowRateDelta,
"CreateFlowFrom: Flow allowance not deducted"
);
}
}
// Assert RTB for all users
_assertRealTimeBalances(superToken_);
_assertGlobalInvariants();
}
/// @notice Updates an ACL flow by the opeartor between a sender and receiver at a given flow rate
/// @dev This helper assumes a valid flow rate with vm.assume and asserts that state has updated as expected.
/// We assert:
/// - The flow info is properly set (flow rate, updated, deposit and owedDeposit are set as expected)
/// - The account flow info has been updated as expected for sender and receiver (delta applied to net flow rates +
/// deposit for sender)
/// - The balance of all test accounts has been updated as expected (balanceSnapshot + streamedAmountSince)
/// - The flow rate allowance has been deducted accordingly (only if flow rate > current flow rate)
/// @param operator The flow operator
/// @param sender The sender of the flow
/// @param receiver The receiver of the flow
/// @param flowRate The desired flow rate
function _helperUpdateFlowFrom(
ISuperToken superToken_,
address operator,
address sender,
address receiver,
int96 flowRate
) internal {
flowRate = _assumeValidFlowRate(flowRate);
// Get Flow Data Before
(
ConstantFlowAgreementV1.FlowData memory flowInfoBefore,
ConstantFlowAgreementV1.FlowData memory senderFlowInfoBefore,
ConstantFlowAgreementV1.FlowData memory receiverFlowInfoBefore
) = _helperGetAllFlowInfo(superToken, sender, receiver);
// Get Flow Operator Data Before
(,,, int96 flowRateAllowanceBefore) = superToken_.getFlowPermissions(sender, operator);
// Execute Update Flow as FlowOperator
vm.startPrank(operator);
superToken_.updateFlowFrom(sender, receiver, flowRate);
vm.stopPrank();
// Update Test State
{
_helperTakeBalanceSnapshot(superToken, sender);
_helperTakeBalanceSnapshot(superToken, receiver);
}
// Assert Flow Data + Account Flow Info for sender/receiver
int96 flowRateDelta = flowRate - flowInfoBefore.flowRate;
{
_assertFlowData(superToken_, sender, receiver, flowRate, block.timestamp, 0);
_assertAccountFlowInfo(sender, flowRateDelta, senderFlowInfoBefore, true);
_assertAccountFlowInfo(receiver, flowRateDelta, receiverFlowInfoBefore, false);
}
// Assert FlowOperator Data
{
(,,, int96 flowRateAllowanceAfter) = superToken_.getFlowPermissions(sender, operator);
if (flowRateAllowanceBefore == type(int96).max) {
assertEq(flowRateAllowanceAfter, flowRateAllowanceBefore, "UpdateFlowFrom: Max flow allowance deducted");
} else {
assertEq(
flowRateAllowanceAfter,