-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathFU.t.sol
More file actions
1401 lines (1237 loc) · 58.2 KB
/
FU.t.sol
File metadata and controls
1401 lines (1237 loc) · 58.2 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.28;
import {IERC20} from "@forge-std/interfaces/IERC20.sol";
import {IFU} from "src/interfaces/IFU.sol";
import {IERC5805} from "src/interfaces/IERC5805.sol";
import {FU} from "src/FU.sol";
import {Buyback} from "src/Buyback.sol";
import {Settings} from "src/core/Settings.sol";
import {applyWhaleLimit} from "src/core/WhaleLimit.sol";
import {Shares} from "src/types/Shares.sol";
import {IUniswapV2Pair} from "src/interfaces/IUniswapV2Pair.sol";
import {IUniswapV2Factory, pairFor} from "src/interfaces/IUniswapV2Factory.sol";
import {ChecksumAddress} from "src/lib/ChecksumAddress.sol";
import {UnsafeMath} from "src/lib/UnsafeMath.sol";
import {uint512, alloc, tmp} from "src/lib/512Math.sol";
import {ItoA} from "src/lib/ItoA.sol";
import {FUDeploy, Common} from "./Deploy.t.sol";
import {StdInvariant} from "@forge-std/StdInvariant.sol";
import {VmSafe, Vm} from "@forge-std/Vm.sol";
import {console} from "@forge-std/console.sol";
// Copied directly from Foundry
abstract contract Bound {
using ItoA for int256;
function bound(uint256 x, uint256 min, uint256 max) internal pure virtual returns (uint256 result) {
require(min <= max, "StdUtils bound(uint256,uint256,uint256): Max is less than min.");
// If x is between min and max, return x directly. This is to ensure that dictionary values
// do not get shifted if the min is nonzero. More info: https://github.com/foundry-rs/forge-std/issues/188
if (x >= min && x <= max) return x;
uint256 size = max - min + 1;
// If the value is 0, 1, 2, 3, wrap that to min, min+1, min+2, min+3. Similarly for the UINT256_MAX side.
// This helps ensure coverage of the min/max values.
if (x <= 3 && size > x) return min + x;
if (x >= type(uint256).max - 3 && size > type(uint256).max - x) return max - (type(uint256).max - x);
// Otherwise, wrap x into the range [min, max], i.e. the range is inclusive.
if (x > max) {
uint256 diff = x - max;
uint256 rem = diff % size;
if (rem == 0) return max;
result = min + rem - 1;
} else if (x < min) {
uint256 diff = min - x;
uint256 rem = diff % size;
if (rem == 0) return min;
result = max - rem + 1;
}
}
function bound(uint256 x, uint256 min, uint256 max, string memory name)
internal
pure
virtual
returns (uint256 result)
{
result = bound(x, min, max);
console.log(name, result);
}
function bound(int256 x, int256 min, int256 max) internal pure virtual returns (int256 result) {
require(min <= max, "StdUtils bound(int256,int256,int256): Max is less than min.");
// Shifting all int256 values to uint256 to use _bound function. The range of two types are:
// int256 : -(2**255) ~ (2**255 - 1)
// uint256: 0 ~ (2**256 - 1)
// So, add 2**255, INT256_MIN_ABS to the integer values.
//
// If the given integer value is -2**255, we cannot use `-uint256(-x)` because of the overflow.
// So, use `~uint256(x) + 1` instead.
uint256 _x = x < 0 ? (uint256(type(int256).min) - ~uint256(x) - 1) : (uint256(x) + uint256(type(int256).min));
uint256 _min =
min < 0 ? (uint256(type(int256).min) - ~uint256(min) - 1) : (uint256(min) + uint256(type(int256).min));
uint256 _max =
max < 0 ? (uint256(type(int256).min) - ~uint256(max) - 1) : (uint256(max) + uint256(type(int256).min));
uint256 y = bound(_x, _min, _max);
// To move it back to int256 value, subtract INT256_MIN_ABS at here.
result = y < uint256(type(int256).min)
? int256(~(uint256(type(int256).min) - y) + 1)
: int256(y - uint256(type(int256).min));
}
function bound(int256 x, int256 min, int256 max, string memory name)
internal
pure
virtual
returns (int256 result)
{
result = bound(x, min, max);
console.log(name, result.itoa());
}
}
function saturatingAdd(uint256 x, uint256 y) pure returns (uint256 r) {
assembly ("memory-safe") {
r := add(x, y)
r := or(r, sub(0x00, lt(r, y)))
}
}
function applyWhaleLimit(uint256 shares0, uint256 shares1, uint256 totalShares)
pure
returns (uint256, uint256, uint256)
{
(Shares shares0_, Shares shares1_, Shares totalShares_) =
applyWhaleLimit(Shares.wrap(shares0), Shares.wrap(shares1), Shares.wrap(totalShares));
return (Shares.unwrap(shares0_), Shares.unwrap(shares1_), Shares.unwrap(totalShares_));
}
function applyWhaleLimit(uint256 shares, uint256 totalShares)
pure
returns (uint256, uint256)
{
(Shares shares_, Shares totalShares_) =
applyWhaleLimit(Shares.wrap(shares), Shares.wrap(totalShares));
return (Shares.unwrap(shares_), Shares.unwrap(totalShares_));
}
interface ListOfInvariants {
function invariant_nonNegativeRebase() external;
function invariant_delegatesNotChanged() external;
function invariant_sumOfShares() external;
function invariant_votingDelegation() external;
function invariant_delegateeZero() external;
function invariant_rebaseQueueContents() external;
}
contract FUGuide is Common, Bound, ListOfInvariants {
Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); // TODO: remove
using ItoA for uint256;
using ChecksumAddress for address;
using UnsafeMath for uint256;
mapping(address => uint256) internal lastBalance;
mapping(address => address) internal shadowDelegates;
uint32 internal shareRatio = 1;
constructor(IFU fu_, Buyback buyback_, address[] memory actors_) {
fu = fu_;
buyback = buyback_;
pair = fu.pair();
setUpActors(actors_);
lastBalance[DEAD] = fu.balanceOf(DEAD);
actors.push(pair);
isActor[pair] = true;
for (uint256 i; i < actors.length; i++) {
address actor = actors[i];
lastBalance[actor] = fu.balanceOf(actor);
}
}
function _sharesSlot(address account) internal pure returns (bytes32 r) {
assembly ("memory-safe") {
mstore(0x00, and(0xffffffffffffffffffffffffffffffffffffffff, account))
mstore(0x20, add(BASE_SLOT, 7))
r := keccak256(0x00, 0x40)
}
}
function _rebaseQueuePrevSlot(address account) internal pure returns (bytes32 r) {
assembly ("memory-safe") {
mstore(0x00, and(0xffffffffffffffffffffffffffffffffffffffff, account))
mstore(0x20, add(0x03, BASE_SLOT))
r := keccak256(0x00, 0x40)
}
}
function _rebaseQueueNextSlot(address account) internal pure returns (bytes32 r) {
unchecked {
return bytes32(uint256(_rebaseQueuePrevSlot(account)) + 1);
}
}
function _rebaseQueueLastTokensSlot(address account) internal pure returns (bytes32 r) {
unchecked {
return bytes32(uint256(_rebaseQueuePrevSlot(account)) + 2);
}
}
function _getShares(address account) external view {
uint256 value = uint256(load(address(fu), _sharesSlot(account)));
assertEq(
value & 0xffffffffff00000000000000000000000000000000000000000000ffffffffff,
0,
string.concat("dirty shares slot: ", value.itoa())
);
value >>= 40;
_revert(value);
}
function getShares(address account) internal view returns (uint256) {
return _staticcall(uint32(this._getShares.selector), account);
}
function setShares(address account, uint256 newShares) internal {
return store(address(fu), _sharesSlot(account), bytes32(newShares << 40));
}
function _getTotalShares() external view {
uint256 value = uint256(load(address(fu), bytes32(uint256(BASE_SLOT) + 2)));
assertEq(value >> 177, 0, string.concat("dirty total supply slot: ", value.itoa()));
assertNotEq(value, 0, "zero total shares");
_revert(value);
}
function getTotalShares() internal view returns (uint256) {
return _staticcall(uint32(this._getTotalShares.selector));
}
function setTotalShares(uint256 newTotalShares) internal {
assertNotEq(newTotalShares, 0, "cannot set zero total shares");
return store(address(fu), bytes32(uint256(BASE_SLOT) + 2), bytes32(newTotalShares));
}
function _getCirculatingTokens() external view {
uint256 value = uint256(load(address(fu), BASE_SLOT));
assertEq(value >> 145, 0, string.concat("dirty circulating tokens slot: ", value.itoa()));
assertNotEq(value, 0, "zero circulating tokens");
_revert(value);
}
function getCirculatingTokens() internal view returns (uint256) {
return _staticcall(uint32(this._getCirculatingTokens.selector));
}
function _getRebaseQueueHead() external view {
uint256 slotValue = uint256(load(address(fu), bytes32(uint256(BASE_SLOT) + 4)));
assertLe(slotValue, type(uint160).max, "dirty rebase queue head slot");
_revert(slotValue);
}
function getRebaseQueueHead() internal view returns (address) {
return address(uint160(_staticcall(uint32(this._getRebaseQueueHead.selector))));
}
function _getRebaseQueuePrev(address account) external view {
uint256 slotValue = uint256(load(address(fu), _rebaseQueuePrevSlot(account)));
assertLe(slotValue, type(uint160).max, "dirty rebase queue prev slot");
_revert(slotValue);
}
function getRebaseQueuePrev(address account) internal view returns (address) {
return address(uint160(_staticcall(uint32(this._getRebaseQueuePrev.selector))));
}
function _getRebaseQueueNext(address account) external view {
uint256 slotValue = uint256(load(address(fu), _rebaseQueueNextSlot(account)));
assertLe(slotValue, type(uint160).max, "dirty rebase queue next slot");
_revert(slotValue);
}
function getRebaseQueueNext(address account) internal view returns (address) {
return address(uint160(_staticcall(uint32(this._getRebaseQueueNext.selector), account)));
}
function updateRebaseQueueLastTokens(address account, uint256 circulatingTokens, uint256 totalShares) internal {
uint256 shares = getShares(account);
(shares, totalShares) = applyWhaleLimit(shares, totalShares);
uint256 tokens = tmp().omul(shares, circulatingTokens).div(totalShares);
return store(address(fu), _rebaseQueueLastTokensSlot(account), bytes32(tokens));
}
function getActor(uint256 actorIndex) internal override returns (address actor, uint256 originalBalance) {
(actor,) = super.getActor(actorIndex);
originalBalance = lastBalance[actor];
lastBalance[actor] = balanceOf(actor);
}
function maybeCreateActor(address newActor) internal override returns (uint256 originalBalance) {
originalBalance = lastBalance[newActor];
if (isActor[newActor]) {
lastBalance[newActor] = balanceOf(newActor);
}
super.maybeCreateActor(newActor);
}
function saveActor(address actor) internal override {
super.saveActor(actor);
lastBalance[actor] = balanceOf(actor);
}
function restoreActor(address actor, uint256 originalBalance) internal {
lastBalance[actor] = originalBalance;
}
function updateLastBalanceForRebaseQueue(VmSafe.Log[] memory logs, address skip0, address skip1) internal {
for (uint256 i; i < logs.length; i++) {
VmSafe.Log memory log = logs[i];
if (log.topics[0] == IERC20.Transfer.selector && log.topics[1] == bytes32(0)) {
address acct = address(uint160(uint256(log.topics[2])));
if (acct == skip0 || acct == skip1) {
continue;
}
lastBalance[acct] = balanceOf(acct);
}
}
}
function updateLastBalanceForRebaseQueue(VmSafe.Log[] memory logs, address skip) internal {
for (uint256 i; i < logs.length; i++) {
VmSafe.Log memory log = logs[i];
if (log.topics[0] == IERC20.Transfer.selector && log.topics[1] == bytes32(0)) {
address acct = address(uint160(uint256(log.topics[2])));
if (acct == skip) {
continue;
}
lastBalance[acct] = balanceOf(acct);
}
}
}
function addActor(address newActor) external {
assume(newActor != address(0));
assume(newActor != DEAD);
assume(newActor != MULTICALL);
assume(newActor != address(fu));
assume(!isActor[newActor]);
maybeCreateActor(newActor);
saveActor(newActor);
}
function warp(uint24 incr) external {
incr = uint24(bound(incr, 4 hours, 2 ** 23 - 1));
warp(getBlockTimestamp() + incr);
}
function setSharesRatio(uint32 newRatio) external {
uint32 oldRatio = shareRatio;
uint256 fudge = 2; // TODO: decrease
newRatio = uint32(
bound(
newRatio,
oldRatio,
Settings.INITIAL_SHARES_RATIO / (Settings.MIN_SHARES_RATIO * fudge),
"shares divisor"
)
);
assume(newRatio != oldRatio);
uint256 total;
{
uint256 shares = getShares(DEAD) * oldRatio / newRatio;
total = shares;
setShares(DEAD, shares);
}
for (uint256 i; i < actors.length; i++) {
address actor = actors[i];
if (actor == pair) {
continue;
}
address delegatee = shadowDelegates[actor];
if (delegatee != address(0)) {
prank(actor);
fu.delegate(address(0));
}
uint256 oldShares = getShares(actor);
uint256 newShares = oldShares * oldRatio / newRatio;
if (oldShares != 0 && newShares == 0) {
// zeroing the shares of an account that previously had nonzero shares corrupts the rebase queue
total += oldShares;
} else {
total += newShares;
setShares(actor, newShares);
}
if (delegatee != address(0)) {
prank(actor);
fu.delegate(delegatee);
}
}
setTotalShares(total);
// Make the rebase queue consistent
{
uint256 circulating = getCirculatingTokens();
for (uint256 i; i < actors.length; i++) {
address actor = actors[i];
if (actor == pair) {
continue;
}
updateRebaseQueueLastTokens(actors[i], circulating, total);
}
updateRebaseQueueLastTokens(DEAD, circulating, total);
}
// Update the shadow of the rebase queue
for (uint256 i; i < actors.length; i++) {
address actor = actors[i];
lastBalance[actor] = balanceOf(actor);
}
lastBalance[DEAD] = balanceOf(DEAD);
shareRatio = newRatio;
}
function _whaleLimit(address acct) external view {
_revert(fu.whaleLimit(acct));
}
function _tax() external view {
_revert(fu.tax());
}
function _getVotes(address acct) external view {
_revert(fu.getVotes(acct));
}
function _totalSupply() external view {
_revert(fu.totalSupply());
}
function _getTotalVotes() external view {
_revert(fu.getTotalVotes());
}
function whaleLimit(address acct) internal view returns (uint256) {
return _staticcall(uint32(this._whaleLimit.selector), acct);
}
function tax() internal view returns (uint256) {
return _staticcall(uint32(this._tax.selector));
}
function getVotes(address acct) internal view returns (uint256) {
return _staticcall(uint32(this._getVotes.selector), acct);
}
function totalSupply() internal view returns (uint256) {
return _staticcall(uint32(this._totalSupply.selector));
}
function getTotalVotes() internal view returns (uint256) {
return _staticcall(uint32(this._getTotalVotes.selector));
}
function _transferShouldFail(address from, address to, uint256 amount, uint256 balance)
internal
view
returns (bool)
{
return from == DEAD || to == DEAD || to == address(fu) || to == from || amount > balance
|| uint160(to) / Settings.ADDRESS_DIVISOR == 0;
}
function transfer(uint256 actorIndex, address to, uint256 amount, bool boundTo, bool boundAmount) external {
(address actor, uint256 originalBalance) = getActor(actorIndex);
if (boundAmount) {
amount = bound(amount, 0, balanceOf(actor), "amount");
} else {
console.log("amount", amount);
}
if (actor == pair) {
assume(amount < balanceOf(actor));
}
uint256 originalBalanceTo;
if (boundTo) {
(to, originalBalanceTo) = getActor(to);
} else {
originalBalanceTo = maybeCreateActor(to);
}
assume(to != MULTICALL); // TODO: remove; it's technically possible even if it's crazy
uint256 beforeBalance = lastBalance[actor];
uint256 beforeBalanceTo = lastBalance[to];
uint256 beforeWhaleLimit = whaleLimit(actor);
uint256 beforeWhaleLimitTo = whaleLimit(to);
bool actorIsWhale = beforeBalance == beforeWhaleLimit;
bool toIsWhaleBefore = beforeBalanceTo == beforeWhaleLimitTo;
uint256 beforeShares = getShares(actor);
uint256 beforeSharesTo = getShares(to);
uint256 beforeCirculating = getCirculatingTokens();
uint256 beforeTotalShares = getTotalShares();
uint256 tax_ = tax();
address rebaseQueueHead = getRebaseQueueHead();
address actorDelegatee = delegates(actor);
address toDelegatee = delegates(actor);
if (!_transferShouldFail(actor, to, amount, beforeBalance)) {
expectEmit(true, true, true, false, address(fu));
emit IERC20.Transfer(actor, to, type(uint256).max);
expectEmit(true, true, true, false, address(fu));
emit IERC20.Transfer(actor, address(0), type(uint256).max);
uint256 divisor = uint160(actor) / Settings.ADDRESS_DIVISOR;
uint256 votes = divisor == 0
? 0
: tmp().omul(amount * Settings.CRAZY_BALANCE_BASIS, beforeTotalShares).div(
beforeCirculating * divisor * Settings.SHARES_TO_VOTES_DIVISOR
);
console.log("votes", votes);
if (votes != 0 && actorDelegatee != toDelegatee) {
if (actorDelegatee != address(0)) {
expectEmit(true, true, true, false, address(fu));
emit IERC5805.DelegateVotesChanged(actorDelegatee, type(uint256).max, type(uint256).max);
}
if (toDelegatee != address(0)) {
expectEmit(true, true, true, false, address(fu));
emit IERC5805.DelegateVotesChanged(toDelegatee, type(uint256).max, type(uint256).max);
}
}
}
vm.recordLogs();
vm.startStateDiffRecording();
prank(actor);
(bool success, bytes memory returndata) = callOptionalReturn(abi.encodeCall(fu.transfer, (to, amount)));
if (success) {
vm.snapshotGasLastCall("transfer");
}
assertEq(success, !_transferShouldFail(actor, to, amount, beforeBalance), "unexpected failure");
VmSafe.AccountAccess[] memory accountAccesses = vm.stopAndReturnStateDiff();
VmSafe.Log[] memory logs = vm.getRecordedLogs();
if (!success) {
assert(
keccak256(returndata)
!= keccak256(hex"4e487b710000000000000000000000000000000000000000000000000000000000000001")
);
assertNoMutation(accountAccesses, logs);
restoreActor(actor, originalBalance);
if (actor != to) {
restoreActor(to, originalBalanceTo);
}
return;
}
saveActor(actor);
saveActor(to);
uint256 logAmountTransfer;
uint256 logAmountBurn;
for (uint256 i; i < logs.length; i++) {
VmSafe.Log memory log = logs[i];
if (
log.topics.length == 3 && log.topics[0] == IERC20.Transfer.selector
&& log.topics[1] == bytes32(uint256(uint160(actor))) && log.topics[2] == bytes32(uint256(uint160(to)))
) {
assertEq(log.emitter, address(fu), "wrong log emitter");
assertEq(log.data.length, 32, "wrong Transfer data length (amount)");
logAmountTransfer = uint256(bytes32(log.data));
log = logs[i + 1];
assertEq(log.topics.length, 3, "wrong burn Transfer event topics");
assertEq(log.topics[0], IERC20.Transfer.selector, "wrong burn Transfer event topic0");
assertEq(log.topics[1], bytes32(uint256(uint160(actor))), "wrong burn Transfer event `from`");
assertEq(log.topics[2], bytes32(0), "wrong burn Transfer event `to` (zero)");
assertEq(log.emitter, address(fu), "wrong log emitter");
assertEq(log.data.length, 32, "wrong burn Transfer data length (amount)");
logAmountBurn = uint256(bytes32(log.data));
// delete both the entries we just looked at from `logs`
assembly ("memory-safe") {
let length := sub(mload(logs), 0x02)
let start := add(0x20, add(shl(0x05, i), logs))
mcopy(start, add(0x40, start), shl(0x05, sub(length, i)))
mstore(logs, length)
}
break;
}
}
uint256 afterBalance = lastBalance[actor];
uint256 afterBalanceTo = lastBalance[to];
uint256 afterWhaleLimit = whaleLimit(actor);
uint256 afterWhaleLimitTo = whaleLimit(to);
bool toIsWhale = afterBalanceTo == afterWhaleLimitTo;
uint256 afterShares = getShares(actor);
uint256 afterSharesTo = getShares(to);
uint256 afterCirculating = getCirculatingTokens();
uint256 afterTotalShares = getTotalShares();
/*
console.log(
string.concat(
"summary"
"\n\tamount: ", amount.itoa(),
"\n\toriginal from balance: ", originalBalance.itoa(),
"\n\tbefore from balance: ", beforeBalance.itoa(),
"\n\tafter from balance: ", afterBalance.itoa(),
"\n\tbefore whale limit: ", beforeWhaleLimit.itoa(),
"\n\tafter whale limit: ", afterWhaleLimit.itoa(),
"\n\toriginal to balance: ", originalBalanceTo.itoa(),
"\n\tbefore to balance: ", beforeBalanceTo.itoa(),
"\n\tafter to balance: ", afterBalanceTo.itoa(),
"\n\tbefore whale limit to: ", beforeWhaleLimitTo.itoa(),
"\n\tafter whale limit to: ", afterWhaleLimitTo.itoa(),
"\n\tbefore total shares: ", beforeTotalShares.itoa(),
"\n\tafter total shares: ", afterTotalShares.itoa(),
"\n\tbefore circulating: ", beforeCirculating.itoa(),
"\n\tafter circulating: ", afterCirculating.itoa(),
"\n\tbefore shares from: ", beforeShares.itoa(),
"\n\tafter shares from: ", afterShares.itoa(),
"\n\tbefore shares to: ", beforeSharesTo.itoa(),
"\n\tafter shares to: ", afterSharesTo.itoa(),
"\n\ttax (basis points): ", tax_.itoa()
)
);
*/
// Check that the whale limit for each account "doesn't" change
if (actor != pair && to != pair) {
assertGe(saturatingAdd(afterWhaleLimit, 1), beforeWhaleLimit, "actor whale limit lower");
assertLe(afterWhaleLimit, saturatingAdd(beforeWhaleLimit, 1), "actor whale limit upper");
assertGe(saturatingAdd(afterWhaleLimitTo, 1), beforeWhaleLimitTo, "to whale limit lower");
assertLe(afterWhaleLimitTo, saturatingAdd(beforeWhaleLimitTo, 1), "to whale limit upper");
}
// Check that the ratio between transferred tokens and burned tokens in the logs represents the tax rate
assertGe(logAmountTransfer + logAmountBurn + 1, amount, "log amount lower");
assertLe(logAmountTransfer + logAmountBurn, amount + 1, "log amount upper");
if (
afterCirculating < beforeCirculating
|| (afterCirculating - beforeCirculating) * (10_000 - tax_) / 10_000
< beforeCirculating.unsafeDivUp(Settings.ANTI_WHALE_DIVISOR)
) {
assertGe(
((logAmountTransfer + logAmountBurn) * tax_).unsafeDivUp(10_000) + 2,
logAmountBurn,
"log tax ratio lower"
);
assertLe((logAmountTransfer + logAmountBurn) * tax_ / 10_000, logAmountBurn + 1, "log tax ratio upper");
} else if (
afterCirculating >= beforeCirculating
&& (afterCirculating - beforeCirculating) * (10_000 - tax_) / 10_000
>= beforeCirculating.unsafeDivUp(Settings.ANTI_WHALE_DIVISOR)
) {
assertLe(
(logAmountTransfer + logAmountBurn) * tax_ / 10_000, logAmountBurn, "log tax ratio upper (insane whale)"
);
}
for (uint256 i; i < logs.length; i++) {
VmSafe.Log memory log = logs[i];
if (log.topics[0] == IERC20.Transfer.selector) {
assertEq(log.emitter, address(fu), "wrong log emitter");
assertEq(log.topics.length, 3, "wrong topics");
assertEq(log.data.length, 32, "wrong Transfer data length (amount)");
assertEq(log.topics[1], bytes32(0), "wrong from address");
assertLe(uint256(log.topics[2]), type(uint160).max, "dirty `to` topic");
address rebaseTo = address(uint160(uint256(log.topics[2])));
// TODO: we need to check the consistency of the queue with the
// head, but this is complex because some elements of the queue
// may be skipped (if their balances are nonincreasing) and also
// the queue may be reordered (if the head pointed at `actor` or
// `to`)
uint256 rebaseAmountTokens = uint256(bytes32(log.data));
uint256 rebaseAmountBalance =
rebaseAmountTokens * (uint160(rebaseTo) / Settings.ADDRESS_DIVISOR) / Settings.CRAZY_BALANCE_BASIS;
uint256 rebaseOriginalBalance;
uint256 rebaseNewBalance;
if (rebaseTo == actor) {
rebaseOriginalBalance = originalBalance;
rebaseNewBalance = beforeBalance;
} else if (rebaseTo == to) {
rebaseOriginalBalance = originalBalanceTo;
rebaseNewBalance = beforeBalanceTo;
} else {
rebaseOriginalBalance = lastBalance[rebaseTo];
rebaseNewBalance = balanceOf(rebaseTo);
}
console.log("original balance", rebaseOriginalBalance);
console.log("new balance", rebaseNewBalance);
uint256 rebaseBalanceDelta = rebaseNewBalance - rebaseOriginalBalance;
console.log("rebaseBalanceDelta", rebaseBalanceDelta);
console.log("rebaseAmountBalance", rebaseAmountBalance);
//console.log("whaleLimit", whaleLimit(rebaseTo));
uint256 fudge = 2; // TODO: decrease
if (!((rebaseTo == actor && toIsWhaleBefore) || (rebaseTo == to && actorIsWhale))) {
assertGe(
rebaseBalanceDelta + fudge,
rebaseAmountBalance,
string.concat("rebase delta lower: ", rebaseTo.toChecksumAddress())
);
}
if (rebaseTo == to ? !toIsWhale : rebaseNewBalance != whaleLimit(rebaseTo)) {
assertLe(
rebaseBalanceDelta,
rebaseAmountBalance + fudge,
string.concat("rebase delta upper: ", rebaseTo.toChecksumAddress())
);
}
}
}
updateLastBalanceForRebaseQueue(logs, actor, to);
// Check that the balance decrease of `actor` is the expected value
if (!toIsWhaleBefore) {
if (actor == pair || amount == beforeBalance) {
assertEq(beforeBalance - afterBalance, amount, "from amount");
} else {
assertGe(beforeBalance - afterBalance + 1, amount, "from amount lower");
assertLe(beforeBalance - afterBalance, amount + 1, "from amount upper");
}
} else {
// It is possible for `actor`'s balance to increase if `to` was over the whale limit by
// more than `amount`. Avoid underflow.
if (beforeBalance >= afterBalance) {
assertLe(beforeBalance - afterBalance, amount + 1, "from amount upper (to whale)");
}
assertTrue(toIsWhale, "to stopped being whale");
}
// Check that the balance increase of `to` is the expected value
uint256 divisor = uint160(actor) / Settings.ADDRESS_DIVISOR;
uint256 multiplier = uint160(to) / Settings.ADDRESS_DIVISOR;
/*
if (actor == pair) {
divisor = 1;
}
if (to == pair) {
multiplier = 1;
}
*/
if (beforeBalance >= afterBalance) {
uint256 sendCrazyLo = beforeBalance - afterBalance;
uint256 sendCrazyHi = amount;
(sendCrazyLo, sendCrazyHi) =
(sendCrazyLo > sendCrazyHi) ? (sendCrazyHi, sendCrazyLo) : (sendCrazyLo, sendCrazyHi);
uint256 sendTokensLo;
uint256 sendTokensHi;
if (amount == beforeBalance) {
(uint256 beforeSharesLimited,, uint256 beforeTotalSharesLimited) =
applyWhaleLimit(beforeShares, beforeSharesTo, beforeTotalShares);
uint512 product = alloc().omul(beforeSharesLimited, beforeCirculating);
sendTokensLo = product.div(beforeTotalSharesLimited);
sendTokensHi = sendTokensLo.unsafeInc(tmp().omul(sendTokensLo, beforeTotalSharesLimited) < product);
} else {
sendTokensLo = sendCrazyLo * Settings.CRAZY_BALANCE_BASIS / divisor;
sendTokensHi = (sendCrazyHi * Settings.CRAZY_BALANCE_BASIS).unsafeDivUp(divisor);
}
//console.log("sendTokensLo", sendTokensLo);
//console.log("sendTokensHi", sendTokensHi);
uint256 receiveTokensXBasisPointsLo = sendTokensLo * (10_000 - tax_);
uint256 receiveTokensXBasisPointsHi = sendTokensHi * (10_000 - tax_);
//console.log("receiveTokensXBasisPointsLo", receiveTokensXBasisPointsLo);
//console.log("receiveTokensXBasisPointsHi", receiveTokensXBasisPointsHi);
uint256 balanceDeltaLo = receiveTokensXBasisPointsLo * multiplier;
uint256 balanceDeltaHi = receiveTokensXBasisPointsHi * multiplier;
//console.log("balanceDeltaLo", balanceDeltaLo);
//console.log("balanceDeltaHi", balanceDeltaHi);
if (!toIsWhale) {
assertGe(
(afterBalanceTo - beforeBalanceTo + 1) * (Settings.CRAZY_BALANCE_BASIS * 10_000)
+ (Settings.CRAZY_BALANCE_BASIS * 10_000 / Settings.MIN_SHARES_RATIO - 1),
balanceDeltaLo,
"to delta lower"
);
} else {
assertGe(
((beforeBalanceTo + 1) * (Settings.CRAZY_BALANCE_BASIS * 10_000) + balanceDeltaHi).unsafeDivUp(
Settings.CRAZY_BALANCE_BASIS * 10_000
),
afterWhaleLimitTo,
"not enough for `to` to become whale"
);
assertGe(afterBalanceTo + 1, beforeBalanceTo, "to balance lower (whale)");
}
if (!actorIsWhale) {
if (afterBalanceTo >= beforeBalanceTo) {
assertLe(
(afterBalanceTo - beforeBalanceTo) * (Settings.CRAZY_BALANCE_BASIS * 10_000),
balanceDeltaHi + (Settings.CRAZY_BALANCE_BASIS * 10_000),
"to delta upper"
);
} else {
assertTrue(toIsWhaleBefore, "to balance decrease not because whale");
assertTrue(toIsWhale, "to balance decrease not because whale");
}
}
} else {
assertTrue(toIsWhaleBefore);
}
// Check that the shares (not balance) accounting is reasonable. The consistency of
// `totalShares` is checked by one of the invariants
if (amount == 0) {
if (to != pair || beforeBalance != 0) {
assertEq(afterCirculating, beforeCirculating, "circulating");
}
if (actorIsWhale || toIsWhale) {
assertGe(beforeTotalShares, afterTotalShares, "shares delta (whale)");
} else if (beforeBalance == 0) {
assertGe(beforeTotalShares, afterTotalShares, "shares delta upper (dust)");
assertLe(beforeTotalShares - beforeShares, afterTotalShares, "shares delta lower (dust)");
} else {
assertEq(beforeTotalShares, afterTotalShares, "shares delta (no-op)");
}
} else {
if (actor == pair) {
assertGe(afterCirculating, beforeCirculating, "circulating (from pair)");
} else if (to == pair) {
assertLe(afterCirculating, beforeCirculating, "circulating (to pair)");
} else {
assertEq(afterCirculating, beforeCirculating, "circulating");
}
assertTrue(
alloc().omul(beforeTotalShares, afterCirculating) > tmp().omul(afterTotalShares, beforeCirculating),
"shares to tokens ratio increased"
);
}
// Check that nobody went over the whale limit
assertLe(
afterShares,
(afterTotalShares - afterShares) / Settings.ANTI_WHALE_DIVISOR_MINUS_ONE - 1,
"from over whale limit"
);
assertLe(
afterSharesTo,
(afterTotalShares - afterSharesTo) / Settings.ANTI_WHALE_DIVISOR_MINUS_ONE - 1,
"to over whale limit"
);
// This seems like it should be obvious, but let's check just to make sure; `actor` cannot
// still be a whale if it sent any tokens
if (amount > 1) {
assertLt(afterBalance, afterWhaleLimit, "from is still a whale");
}
}
function delegate(uint256 actorIndex, address delegatee) external {
(address actor,) = super.getActor(actorIndex);
assume(actor != pair);
super.maybeCreateActor(delegatee);
address oldDelegatee = shadowDelegates[actor];
uint256 oldVotes = getVotes(oldDelegatee);
uint256 newVotes = getVotes(delegatee);
uint256 votes = getShares(actor) / Settings.SHARES_TO_VOTES_DIVISOR;
expectEmit(true, true, true, true, address(fu));
emit IERC5805.DelegateChanged(actor, oldDelegatee, delegatee);
if (votes != 0 && oldDelegatee != delegatee) {
if (oldDelegatee != address(0)) {
expectEmit(true, true, true, true, address(fu));
emit IERC5805.DelegateVotesChanged(oldDelegatee, oldVotes, oldVotes - votes);
}
if (delegatee != address(0)) {
expectEmit(true, true, true, true, address(fu));
emit IERC5805.DelegateVotesChanged(delegatee, newVotes, newVotes + votes);
}
}
prank(actor);
fu.delegate(delegatee); // ERC5805 requires that this function return nothing or revert
assertEq(delegates(actor), delegatee);
super.saveActor(actor);
shadowDelegates[actor] = delegates(actor);
if (delegatee != address(0) && delegatee != DEAD && delegatee != address(fu)) {
super.saveActor(delegatee);
}
}
function _burnShouldFail(address from, uint256 amount, uint256 balance) internal pure returns (bool) {
return from == DEAD || amount > balance;
}
function burn(uint256 actorIndex, uint256 amount, bool boundAmount) external {
(address actor, uint256 originalBalance) = getActor(actorIndex);
if (boundAmount) {
amount = bound(amount, 0, balanceOf(actor), "amount");
} else {
console.log("amount", amount);
}
assume(actor != pair || amount == 0);
address delegatee = shadowDelegates[actor];
uint256 beforeBalance = lastBalance[actor];
uint256 beforeWhaleLimit = whaleLimit(actor);
uint256 beforeSupply = totalSupply();
uint256 beforeTotalShares = getTotalShares();
uint256 beforeCirculating = getCirculatingTokens();
uint256 beforeVotingPower = getVotes(delegatee);
uint256 beforeShares = getShares(actor);
address actorDelegatee = delegates(actor);
if (!_burnShouldFail(actor, amount, beforeBalance)) {
expectEmit(true, true, true, true, address(fu));
emit IERC20.Transfer(actor, address(0), amount);
uint256 divisor = uint160(actor) / Settings.ADDRESS_DIVISOR;
uint256 votes = divisor == 0
? 0
: tmp().omul(amount * Settings.CRAZY_BALANCE_BASIS, beforeTotalShares).div(
beforeCirculating * divisor * Settings.SHARES_TO_VOTES_DIVISOR
);
// TODO: `votes > 1` should be `votes != 0`, but there appears to be some rounding error in play here.
if (votes > 1 && actorDelegatee != address(0)) {
expectEmit(true, true, true, false, address(fu));
emit IERC5805.DelegateVotesChanged(actorDelegatee, type(uint256).max, type(uint256).max);
}
}
vm.recordLogs();
vm.startStateDiffRecording();
prank(actor);
(bool success, bytes memory returndata) = callOptionalReturn(abi.encodeCall(fu.burn, (amount)));
if (success) {
vm.snapshotGasLastCall("burn");
}
assertEq(success, !_burnShouldFail(actor, amount, beforeBalance), "unexpected failure");
VmSafe.AccountAccess[] memory accountAccesses = vm.stopAndReturnStateDiff();
VmSafe.Log[] memory logs = vm.getRecordedLogs();
if (!success) {
assert(
keccak256(returndata)
!= keccak256(hex"4e487b710000000000000000000000000000000000000000000000000000000000000001")
);
assertNoMutation(accountAccesses, logs);
restoreActor(actor, originalBalance);
return;
}
saveActor(actor);
uint256 afterBalance = lastBalance[actor];
uint256 afterSupply = totalSupply();
uint256 afterTotalShares = getTotalShares();
uint256 afterCirculating = getCirculatingTokens();
uint256 afterVotingPower = getVotes(delegatee);
uint256 afterShares = getShares(actor);
for (uint256 i; i < logs.length; i++) {
VmSafe.Log memory log = logs[i];
if (log.topics[0] == IERC20.Transfer.selector && log.topics[1] == bytes32(0)) {
assertEq(log.emitter, address(fu), "wrong log emitter");
assertEq(log.topics.length, 3, "wrong topics");
assertEq(log.data.length, 32, "wrong Transfer data length (amount)");
assertLe(uint256(log.topics[2]), type(uint160).max, "dirty `to` topic");
address rebaseTo = address(uint160(uint256(log.topics[2])));
// TODO: see TODO in similar block in `transfer`
uint256 rebaseAmountTokens = uint256(bytes32(log.data));
uint256 rebaseAmountBalance =
rebaseAmountTokens * (uint160(rebaseTo) / Settings.ADDRESS_DIVISOR) / Settings.CRAZY_BALANCE_BASIS;
uint256 rebaseOriginalBalance;
uint256 rebaseNewBalance;
if (rebaseTo == actor) {
rebaseOriginalBalance = originalBalance;
rebaseNewBalance = beforeBalance;
} else {
rebaseOriginalBalance = lastBalance[rebaseTo];
rebaseNewBalance = balanceOf(rebaseTo);
}
console.log("original balance", rebaseOriginalBalance);
console.log("new balance", rebaseNewBalance);
uint256 rebaseBalanceDelta = rebaseNewBalance - rebaseOriginalBalance;
console.log("rebaseBalanceDelta", rebaseBalanceDelta);
console.log("rebaseAmountBalance", rebaseAmountBalance);
//console.log("whaleLimit", whaleLimit(rebaseTo));
uint256 fudge = 2; // TODO: decrease
assertGe(
rebaseBalanceDelta + fudge,
rebaseAmountBalance,
string.concat("rebase delta lower: ", rebaseTo.toChecksumAddress())
);
if (rebaseNewBalance != whaleLimit(rebaseTo)) {
assertLe(
rebaseBalanceDelta,
rebaseAmountBalance + fudge,
string.concat("rebase delta upper: ", rebaseTo.toChecksumAddress())
);
}
}
}
updateLastBalanceForRebaseQueue(logs, actor);
if (beforeShares == 0) {
assertTrue(
alloc().omul(beforeTotalShares, afterCirculating) == tmp().omul(afterTotalShares, beforeCirculating),
"shares to tokens ratio (no shares)"
);
} else if (beforeBalance == 0) {
assertTrue(
alloc().omul(beforeTotalShares, afterCirculating) > tmp().omul(afterTotalShares, beforeCirculating),
"shares to tokens ratio (dust)"
);
} else if (amount == 0) {