This repository has been archived by the owner on May 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TwabController.sol
872 lines (779 loc) · 33.8 KB
/
TwabController.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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import { SafeCast } from "openzeppelin/utils/math/SafeCast.sol";
import { TwabLib } from "./libraries/TwabLib.sol";
import { ObservationLib } from "./libraries/ObservationLib.sol";
/// @notice Emitted when an account already points to the same delegate address that is being set
error SameDelegateAlreadySet(address delegate);
/// @notice Emitted when an account tries to transfer to the sponsorship address
error CannotTransferToSponsorshipAddress();
/// @notice Emitted when the period length is too short
error PeriodLengthTooShort();
/// @notice Emitted when the period offset is not in the past.
/// @param periodOffset The period offset that was passed in
error PeriodOffsetInFuture(uint32 periodOffset);
/// @notice Emitted when a user tries to mint or transfer to the zero address
error TransferToZeroAddress();
// The minimum period length
uint32 constant MINIMUM_PERIOD_LENGTH = 1 hours;
// Allows users to revoke their chances to win by delegating to the sponsorship address.
address constant SPONSORSHIP_ADDRESS = address(1);
/**
* @title PoolTogether V5 Time-Weighted Average Balance Controller
* @author PoolTogether Inc. & G9 Software Inc.
* @dev Time-Weighted Average Balance Controller for ERC20 tokens.
* @notice This TwabController uses the TwabLib to provide token balances and on-chain historical
lookups to a user(s) time-weighted average balance. Each user is mapped to an
Account struct containing the TWAB history (ring buffer) and ring buffer parameters.
Every token.transfer() creates a new TWAB observation. The new TWAB observation is
stored in the circular ring buffer as either a new observation or rewriting a
previous observation with new parameters. One observation per period is stored.
The TwabLib guarantees minimum 1 year of search history if a period is a day.
*/
contract TwabController {
using SafeCast for uint256;
/// @notice Sets the minimum period length for Observations. When a period elapses, a new Observation is recorded, otherwise the most recent Observation is updated.
uint32 public immutable PERIOD_LENGTH;
/// @notice Sets the beginning timestamp for the first period. This allows us to maximize storage as well as line up periods with a chosen timestamp.
/// @dev Ensure that the PERIOD_OFFSET is in the past.
uint32 public immutable PERIOD_OFFSET;
/* ============ State ============ */
/// @notice Record of token holders TWABs for each account for each vault.
mapping(address => mapping(address => TwabLib.Account)) internal userObservations;
/// @notice Record of tickets total supply and ring buff parameters used for observation.
mapping(address => TwabLib.Account) internal totalSupplyObservations;
/// @notice vault => user => delegate.
mapping(address => mapping(address => address)) internal delegates;
/* ============ Events ============ */
/**
* @notice Emitted when a balance or delegateBalance is increased.
* @param vault the vault for which the balance increased
* @param user the users whose balance increased
* @param amount the amount the balance increased by
* @param delegateAmount the amount the delegateBalance increased by
*/
event IncreasedBalance(
address indexed vault,
address indexed user,
uint96 amount,
uint96 delegateAmount
);
/**
* @notice Emitted when a balance or delegateBalance is decreased.
* @param vault the vault for which the balance decreased
* @param user the users whose balance decreased
* @param amount the amount the balance decreased by
* @param delegateAmount the amount the delegateBalance decreased by
*/
event DecreasedBalance(
address indexed vault,
address indexed user,
uint96 amount,
uint96 delegateAmount
);
/**
* @notice Emitted when an Observation is recorded to the Ring Buffer.
* @param vault the vault for which the Observation was recorded
* @param user the users whose Observation was recorded
* @param balance the resulting balance
* @param delegateBalance the resulting delegated balance
* @param isNew whether the observation is new or not
* @param observation the observation that was created or updated
*/
event ObservationRecorded(
address indexed vault,
address indexed user,
uint96 balance,
uint96 delegateBalance,
bool isNew,
ObservationLib.Observation observation
);
/**
* @notice Emitted when a user delegates their balance to another address.
* @param vault the vault for which the balance was delegated
* @param delegator the user who delegated their balance
* @param delegate the user who received the delegated balance
*/
event Delegated(address indexed vault, address indexed delegator, address indexed delegate);
/**
* @notice Emitted when the total supply or delegateTotalSupply is increased.
* @param vault the vault for which the total supply increased
* @param amount the amount the total supply increased by
* @param delegateAmount the amount the delegateTotalSupply increased by
*/
event IncreasedTotalSupply(address indexed vault, uint96 amount, uint96 delegateAmount);
/**
* @notice Emitted when the total supply or delegateTotalSupply is decreased.
* @param vault the vault for which the total supply decreased
* @param amount the amount the total supply decreased by
* @param delegateAmount the amount the delegateTotalSupply decreased by
*/
event DecreasedTotalSupply(address indexed vault, uint96 amount, uint96 delegateAmount);
/**
* @notice Emitted when a Total Supply Observation is recorded to the Ring Buffer.
* @param vault the vault for which the Observation was recorded
* @param balance the resulting balance
* @param delegateBalance the resulting delegated balance
* @param isNew whether the observation is new or not
* @param observation the observation that was created or updated
*/
event TotalSupplyObservationRecorded(
address indexed vault,
uint96 balance,
uint96 delegateBalance,
bool isNew,
ObservationLib.Observation observation
);
/* ============ Constructor ============ */
/**
* @notice Construct a new TwabController.
* @dev Reverts if the period offset is in the future.
* @param _periodLength Sets the minimum period length for Observations. When a period elapses, a new Observation
* is recorded, otherwise the most recent Observation is updated.
* @param _periodOffset Sets the beginning timestamp for the first period. This allows us to maximize storage as well
* as line up periods with a chosen timestamp.
*/
constructor(uint32 _periodLength, uint32 _periodOffset) {
if (_periodLength < MINIMUM_PERIOD_LENGTH) {
revert PeriodLengthTooShort();
}
if (_periodOffset > block.timestamp) {
revert PeriodOffsetInFuture(_periodOffset);
}
PERIOD_LENGTH = _periodLength;
PERIOD_OFFSET = _periodOffset;
}
/* ============ External Read Functions ============ */
/**
* @notice Returns whether the TwabController has been shutdown at the given timestamp
* If the twab is queried at or after this time, whether an absolute timestamp or time range, it will return 0.
* @dev This function will return true for any timestamp after the lastObservationAt()
* @param timestamp The timestamp to check
* @return True if the TwabController is shutdown at the given timestamp, false otherwise.
*/
function isShutdownAt(uint256 timestamp) external view returns (bool) {
return TwabLib.isShutdownAt(timestamp, PERIOD_LENGTH, PERIOD_OFFSET);
}
/**
* @notice Computes the timestamp after which no more observations will be made.
* @return The largest timestamp at which the TwabController can record a new observation.
*/
function lastObservationAt() external view returns (uint256) {
return TwabLib.lastObservationAt(PERIOD_LENGTH, PERIOD_OFFSET);
}
/**
* @notice Loads the current TWAB Account data for a specific vault stored for a user.
* @dev Note this is a very expensive function
* @param vault the vault for which the data is being queried
* @param user the user whose data is being queried
* @return The current TWAB Account data of the user
*/
function getAccount(address vault, address user) external view returns (TwabLib.Account memory) {
return userObservations[vault][user];
}
/**
* @notice Loads the current total supply TWAB Account data for a specific vault.
* @dev Note this is a very expensive function
* @param vault the vault for which the data is being queried
* @return The current total supply TWAB Account data
*/
function getTotalSupplyAccount(address vault) external view returns (TwabLib.Account memory) {
return totalSupplyObservations[vault];
}
/**
* @notice The current token balance of a user for a specific vault.
* @param vault the vault for which the balance is being queried
* @param user the user whose balance is being queried
* @return The current token balance of the user
*/
function balanceOf(address vault, address user) external view returns (uint256) {
return userObservations[vault][user].details.balance;
}
/**
* @notice The total supply of tokens for a vault.
* @param vault the vault for which the total supply is being queried
* @return The total supply of tokens for a vault
*/
function totalSupply(address vault) external view returns (uint256) {
return totalSupplyObservations[vault].details.balance;
}
/**
* @notice The total delegated amount of tokens for a vault.
* @dev Delegated balance is not 1:1 with the token total supply. Users may delegate their
* balance to the sponsorship address, which will result in those tokens being subtracted
* from the total.
* @param vault the vault for which the total delegated supply is being queried
* @return The total delegated amount of tokens for a vault
*/
function totalSupplyDelegateBalance(address vault) external view returns (uint256) {
return totalSupplyObservations[vault].details.delegateBalance;
}
/**
* @notice The current delegate of a user for a specific vault.
* @param vault the vault for which the delegate balance is being queried
* @param user the user whose delegate balance is being queried
* @return The current delegate balance of the user
*/
function delegateOf(address vault, address user) external view returns (address) {
return _delegateOf(vault, user);
}
/**
* @notice The current delegateBalance of a user for a specific vault.
* @dev the delegateBalance is the sum of delegated balance to this user
* @param vault the vault for which the delegateBalance is being queried
* @param user the user whose delegateBalance is being queried
* @return The current delegateBalance of the user
*/
function delegateBalanceOf(address vault, address user) external view returns (uint256) {
return userObservations[vault][user].details.delegateBalance;
}
/**
* @notice Looks up a users balance at a specific time in the past.
* @param vault the vault for which the balance is being queried
* @param user the user whose balance is being queried
* @param periodEndOnOrAfterTime The time in the past for which the balance is being queried. The time will be snapped to a period end time on or after the timestamp.
* @return The balance of the user at the target time
*/
function getBalanceAt(
address vault,
address user,
uint256 periodEndOnOrAfterTime
) external view returns (uint256) {
TwabLib.Account storage _account = userObservations[vault][user];
return
TwabLib.getBalanceAt(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account.observations,
_account.details,
_periodEndOnOrAfter(periodEndOnOrAfterTime)
);
}
/**
* @notice Looks up the total supply at a specific time in the past.
* @param vault the vault for which the total supply is being queried
* @param periodEndOnOrAfterTime The time in the past for which the balance is being queried. The time will be snapped to a period end time on or after the timestamp.
* @return The total supply at the target time
*/
function getTotalSupplyAt(
address vault,
uint256 periodEndOnOrAfterTime
) external view returns (uint256) {
TwabLib.Account storage _account = totalSupplyObservations[vault];
return
TwabLib.getBalanceAt(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account.observations,
_account.details,
_periodEndOnOrAfter(periodEndOnOrAfterTime)
);
}
/**
* @notice Looks up the average balance of a user between two timestamps.
* @dev Timestamps are Unix timestamps denominated in seconds
* @param vault the vault for which the average balance is being queried
* @param user the user whose average balance is being queried
* @param startTime the start of the time range for which the average balance is being queried. The time will be snapped to a period end time on or after the timestamp.
* @param endTime the end of the time range for which the average balance is being queried. The time will be snapped to a period end time on or after the timestamp.
* @return The average balance of the user between the two timestamps
*/
function getTwabBetween(
address vault,
address user,
uint256 startTime,
uint256 endTime
) external view returns (uint256) {
TwabLib.Account storage _account = userObservations[vault][user];
// We snap the timestamps to the period end on or after the timestamp because the total supply records will be sparsely populated.
// if two users update during a period, then the total supply observation will only exist for the last one.
return
TwabLib.getTwabBetween(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account.observations,
_account.details,
_periodEndOnOrAfter(startTime),
_periodEndOnOrAfter(endTime)
);
}
/**
* @notice Looks up the average total supply between two timestamps.
* @dev Timestamps are Unix timestamps denominated in seconds
* @param vault the vault for which the average total supply is being queried
* @param startTime the start of the time range for which the average total supply is being queried
* @param endTime the end of the time range for which the average total supply is being queried
* @return The average total supply between the two timestamps
*/
function getTotalSupplyTwabBetween(
address vault,
uint256 startTime,
uint256 endTime
) external view returns (uint256) {
TwabLib.Account storage _account = totalSupplyObservations[vault];
// We snap the timestamps to the period end on or after the timestamp because the total supply records will be sparsely populated.
// if two users update during a period, then the total supply observation will only exist for the last one.
return
TwabLib.getTwabBetween(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account.observations,
_account.details,
_periodEndOnOrAfter(startTime),
_periodEndOnOrAfter(endTime)
);
}
/**
* @notice Computes the period end timestamp on or after the given timestamp.
* @param _timestamp The timestamp to check
* @return The end timestamp of the period that ends on or immediately after the given timestamp
*/
function periodEndOnOrAfter(uint256 _timestamp) external view returns (uint256) {
return _periodEndOnOrAfter(_timestamp);
}
/**
* @notice Computes the period end timestamp on or after the given timestamp.
* @param _timestamp The timestamp to compute the period end time for
* @return A period end time.
*/
function _periodEndOnOrAfter(uint256 _timestamp) internal view returns (uint256) {
if (_timestamp < PERIOD_OFFSET) {
return PERIOD_OFFSET;
}
if ((_timestamp - PERIOD_OFFSET) % PERIOD_LENGTH == 0) {
return _timestamp;
}
uint256 period = TwabLib.getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, _timestamp);
return TwabLib.getPeriodEndTime(PERIOD_LENGTH, PERIOD_OFFSET, period);
}
/**
* @notice Looks up the newest observation for a user.
* @param vault the vault for which the observation is being queried
* @param user the user whose observation is being queried
* @return index The index of the observation
* @return observation The observation of the user
*/
function getNewestObservation(
address vault,
address user
) external view returns (uint16, ObservationLib.Observation memory) {
TwabLib.Account storage _account = userObservations[vault][user];
return TwabLib.getNewestObservation(_account.observations, _account.details);
}
/**
* @notice Looks up the oldest observation for a user.
* @param vault the vault for which the observation is being queried
* @param user the user whose observation is being queried
* @return index The index of the observation
* @return observation The observation of the user
*/
function getOldestObservation(
address vault,
address user
) external view returns (uint16, ObservationLib.Observation memory) {
TwabLib.Account storage _account = userObservations[vault][user];
return TwabLib.getOldestObservation(_account.observations, _account.details);
}
/**
* @notice Looks up the newest total supply observation for a vault.
* @param vault the vault for which the observation is being queried
* @return index The index of the observation
* @return observation The total supply observation
*/
function getNewestTotalSupplyObservation(
address vault
) external view returns (uint16, ObservationLib.Observation memory) {
TwabLib.Account storage _account = totalSupplyObservations[vault];
return TwabLib.getNewestObservation(_account.observations, _account.details);
}
/**
* @notice Looks up the oldest total supply observation for a vault.
* @param vault the vault for which the observation is being queried
* @return index The index of the observation
* @return observation The total supply observation
*/
function getOldestTotalSupplyObservation(
address vault
) external view returns (uint16, ObservationLib.Observation memory) {
TwabLib.Account storage _account = totalSupplyObservations[vault];
return TwabLib.getOldestObservation(_account.observations, _account.details);
}
/**
* @notice Calculates the period a timestamp falls into.
* @param time The timestamp to check
* @return period The period the timestamp falls into
*/
function getTimestampPeriod(uint256 time) external view returns (uint256) {
return TwabLib.getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, time);
}
/**
* @notice Checks if the given timestamp is before the current overwrite period.
* @param time The timestamp to check
* @return True if the given time is finalized, false if it's during the current overwrite period.
*/
function hasFinalized(uint256 time) external view returns (bool) {
return TwabLib.hasFinalized(PERIOD_LENGTH, PERIOD_OFFSET, time);
}
/**
* @notice Computes the timestamp at which the current overwrite period started.
* @dev The overwrite period is the period during which observations are collated.
* @return period The timestamp at which the current overwrite period started.
*/
function currentOverwritePeriodStartedAt() external view returns (uint256) {
return TwabLib.currentOverwritePeriodStartedAt(PERIOD_LENGTH, PERIOD_OFFSET);
}
/* ============ External Write Functions ============ */
/**
* @notice Mints new balance and delegateBalance for a given user.
* @dev Note that if the provided user to mint to is delegating that the delegate's
* delegateBalance will be updated.
* @dev Mint is expected to be called by the Vault.
* @param _to The address to mint balance and delegateBalance to
* @param _amount The amount to mint
*/
function mint(address _to, uint96 _amount) external {
if (_to == address(0)) {
revert TransferToZeroAddress();
}
_transferBalance(msg.sender, address(0), _to, _amount);
}
/**
* @notice Burns balance and delegateBalance for a given user.
* @dev Note that if the provided user to burn from is delegating that the delegate's
* delegateBalance will be updated.
* @dev Burn is expected to be called by the Vault.
* @param _from The address to burn balance and delegateBalance from
* @param _amount The amount to burn
*/
function burn(address _from, uint96 _amount) external {
_transferBalance(msg.sender, _from, address(0), _amount);
}
/**
* @notice Transfers balance and delegateBalance from a given user.
* @dev Note that if the provided user to transfer from is delegating that the delegate's
* delegateBalance will be updated.
* @param _from The address to transfer the balance and delegateBalance from
* @param _to The address to transfer balance and delegateBalance to
* @param _amount The amount to transfer
*/
function transfer(address _from, address _to, uint96 _amount) external {
if (_to == address(0)) {
revert TransferToZeroAddress();
}
_transferBalance(msg.sender, _from, _to, _amount);
}
/**
* @notice Sets a delegate for a user which forwards the delegateBalance tied to the user's
* balance to the delegate's delegateBalance.
* @param _vault The vault for which the delegate is being set
* @param _to the address to delegate to
*/
function delegate(address _vault, address _to) external {
_delegate(_vault, msg.sender, _to);
}
/**
* @notice Delegate user balance to the sponsorship address.
* @dev Must only be called by the Vault contract.
* @param _from Address of the user delegating their balance to the sponsorship address.
*/
function sponsor(address _from) external {
_delegate(msg.sender, _from, SPONSORSHIP_ADDRESS);
}
/* ============ Internal Functions ============ */
/**
* @notice Transfers a user's vault balance from one address to another.
* @dev If the user is delegating, their delegate's delegateBalance is also updated.
* @dev If we are minting or burning tokens then the total supply is also updated.
* @param _vault the vault for which the balance is being transferred
* @param _from the address from which the balance is being transferred
* @param _to the address to which the balance is being transferred
* @param _amount the amount of balance being transferred
*/
function _transferBalance(address _vault, address _from, address _to, uint96 _amount) internal {
if (_to == SPONSORSHIP_ADDRESS) {
revert CannotTransferToSponsorshipAddress();
}
if (_from == _to) {
return;
}
// If we are transferring tokens from a delegated account to an undelegated account
address _fromDelegate = _delegateOf(_vault, _from);
address _toDelegate = _delegateOf(_vault, _to);
if (_from != address(0)) {
bool _isFromDelegate = _fromDelegate == _from;
_decreaseBalances(_vault, _from, _amount, _isFromDelegate ? _amount : 0);
// If the user is not delegating to themself, decrease the delegate's delegateBalance
// If the user is delegating to the sponsorship address, don't adjust the delegateBalance
if (!_isFromDelegate && _fromDelegate != SPONSORSHIP_ADDRESS) {
_decreaseBalances(_vault, _fromDelegate, 0, _amount);
}
// Burn balance if we're transferring to address(0)
// Burn delegateBalance if we're transferring to address(0) and burning from an address that is not delegating to the sponsorship address
// Burn delegateBalance if we're transferring to an address delegating to the sponsorship address from an address that isn't delegating to the sponsorship address
if (
_to == address(0) ||
(_toDelegate == SPONSORSHIP_ADDRESS && _fromDelegate != SPONSORSHIP_ADDRESS)
) {
// If the user is delegating to the sponsorship address, don't adjust the total supply delegateBalance
_decreaseTotalSupplyBalances(
_vault,
_to == address(0) ? _amount : 0,
(_to == address(0) && _fromDelegate != SPONSORSHIP_ADDRESS) ||
(_toDelegate == SPONSORSHIP_ADDRESS && _fromDelegate != SPONSORSHIP_ADDRESS)
? _amount
: 0
);
}
}
// If we are transferring tokens to an address other than address(0)
if (_to != address(0)) {
bool _isToDelegate = _toDelegate == _to;
// If the user is delegating to themself, increase their delegateBalance
_increaseBalances(_vault, _to, _amount, _isToDelegate ? _amount : 0);
// Otherwise, increase their delegates delegateBalance if it is not the sponsorship address
if (!_isToDelegate && _toDelegate != SPONSORSHIP_ADDRESS) {
_increaseBalances(_vault, _toDelegate, 0, _amount);
}
// Mint balance if we're transferring from address(0)
// Mint delegateBalance if we're transferring from address(0) and to an address not delegating to the sponsorship address
// Mint delegateBalance if we're transferring from an address delegating to the sponsorship address to an address that isn't delegating to the sponsorship address
if (
_from == address(0) ||
(_fromDelegate == SPONSORSHIP_ADDRESS && _toDelegate != SPONSORSHIP_ADDRESS)
) {
_increaseTotalSupplyBalances(
_vault,
_from == address(0) ? _amount : 0,
(_from == address(0) && _toDelegate != SPONSORSHIP_ADDRESS) ||
(_fromDelegate == SPONSORSHIP_ADDRESS && _toDelegate != SPONSORSHIP_ADDRESS)
? _amount
: 0
);
}
}
}
/**
* @notice Looks up the delegate of a user.
* @param _vault the vault for which the user's delegate is being queried
* @param _user the address to query the delegate of
* @return The address of the user's delegate
*/
function _delegateOf(address _vault, address _user) internal view returns (address) {
address _userDelegate;
if (_user != address(0)) {
_userDelegate = delegates[_vault][_user];
// If the user has not delegated, then the user is the delegate
if (_userDelegate == address(0)) {
_userDelegate = _user;
}
}
return _userDelegate;
}
/**
* @notice Transfers a user's vault delegateBalance from one address to another.
* @param _vault the vault for which the delegateBalance is being transferred
* @param _fromDelegate the address from which the delegateBalance is being transferred
* @param _toDelegate the address to which the delegateBalance is being transferred
* @param _amount the amount of delegateBalance being transferred
*/
function _transferDelegateBalance(
address _vault,
address _fromDelegate,
address _toDelegate,
uint96 _amount
) internal {
// If we are transferring tokens from a delegated account to an undelegated account
if (_fromDelegate != address(0) && _fromDelegate != SPONSORSHIP_ADDRESS) {
_decreaseBalances(_vault, _fromDelegate, 0, _amount);
// If we are delegating to the zero address, decrease total supply
// If we are delegating to the sponsorship address, decrease total supply
if (_toDelegate == address(0) || _toDelegate == SPONSORSHIP_ADDRESS) {
_decreaseTotalSupplyBalances(_vault, 0, _amount);
}
}
// If we are transferring tokens from an undelegated account to a delegated account
if (_toDelegate != address(0) && _toDelegate != SPONSORSHIP_ADDRESS) {
_increaseBalances(_vault, _toDelegate, 0, _amount);
// If we are removing delegation from the zero address, increase total supply
// If we are removing delegation from the sponsorship address, increase total supply
if (_fromDelegate == address(0) || _fromDelegate == SPONSORSHIP_ADDRESS) {
_increaseTotalSupplyBalances(_vault, 0, _amount);
}
}
}
/**
* @notice Sets a delegate for a user which forwards the delegateBalance tied to the user's
* balance to the delegate's delegateBalance. "Sponsoring" means the funds aren't delegated
* to anyone; this can be done by passing address(0) or the SPONSORSHIP_ADDRESS as the delegate.
* @param _vault The vault for which the delegate is being set
* @param _from the address to delegate from
* @param _to the address to delegate to
*/
function _delegate(address _vault, address _from, address _to) internal {
address _currentDelegate = _delegateOf(_vault, _from);
// address(0) is interpreted as sponsoring, so they don't need to know the sponsorship address.
address to = _to == address(0) ? SPONSORSHIP_ADDRESS : _to;
if (to == _currentDelegate) {
revert SameDelegateAlreadySet(to);
}
delegates[_vault][_from] = to;
_transferDelegateBalance(
_vault,
_currentDelegate,
_to,
SafeCast.toUint96(userObservations[_vault][_from].details.balance)
);
emit Delegated(_vault, _from, to);
}
/**
* @notice Increases a user's balance and delegateBalance for a specific vault.
* @param _vault the vault for which the balance is being increased
* @param _user the address of the user whose balance is being increased
* @param _amount the amount of balance being increased
* @param _delegateAmount the amount of delegateBalance being increased
*/
function _increaseBalances(
address _vault,
address _user,
uint96 _amount,
uint96 _delegateAmount
) internal {
TwabLib.Account storage _account = userObservations[_vault][_user];
(
ObservationLib.Observation memory _observation,
bool _isNewObservation,
bool _isObservationRecorded,
TwabLib.AccountDetails memory accountDetails
) = TwabLib.increaseBalances(PERIOD_LENGTH, PERIOD_OFFSET, _account, _amount, _delegateAmount);
// Always emit the balance change event
if (_amount != 0 || _delegateAmount != 0) {
emit IncreasedBalance(_vault, _user, _amount, _delegateAmount);
}
// Conditionally emit the observation recorded event
if (_isObservationRecorded) {
emit ObservationRecorded(
_vault,
_user,
accountDetails.balance,
accountDetails.delegateBalance,
_isNewObservation,
_observation
);
}
}
/**
* @notice Decreases the a user's balance and delegateBalance for a specific vault.
* @param _vault the vault for which the totalSupply balance is being decreased
* @param _amount the amount of balance being decreased
* @param _delegateAmount the amount of delegateBalance being decreased
*/
function _decreaseBalances(
address _vault,
address _user,
uint96 _amount,
uint96 _delegateAmount
) internal {
TwabLib.Account storage _account = userObservations[_vault][_user];
(
ObservationLib.Observation memory _observation,
bool _isNewObservation,
bool _isObservationRecorded,
TwabLib.AccountDetails memory accountDetails
) = TwabLib.decreaseBalances(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account,
_amount,
_delegateAmount,
"TC/observation-burn-lt-delegate-balance"
);
// Always emit the balance change event
if (_amount != 0 || _delegateAmount != 0) {
emit DecreasedBalance(_vault, _user, _amount, _delegateAmount);
}
// Conditionally emit the observation recorded event
if (_isObservationRecorded) {
emit ObservationRecorded(
_vault,
_user,
accountDetails.balance,
accountDetails.delegateBalance,
_isNewObservation,
_observation
);
}
}
/**
* @notice Decreases the totalSupply balance and delegateBalance for a specific vault.
* @param _vault the vault for which the totalSupply balance is being decreased
* @param _amount the amount of balance being decreased
* @param _delegateAmount the amount of delegateBalance being decreased
*/
function _decreaseTotalSupplyBalances(
address _vault,
uint96 _amount,
uint96 _delegateAmount
) internal {
TwabLib.Account storage _account = totalSupplyObservations[_vault];
(
ObservationLib.Observation memory _observation,
bool _isNewObservation,
bool _isObservationRecorded,
TwabLib.AccountDetails memory accountDetails
) = TwabLib.decreaseBalances(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account,
_amount,
_delegateAmount,
"TC/burn-amount-exceeds-total-supply-balance"
);
// Always emit the balance change event
if (_amount != 0 || _delegateAmount != 0) {
emit DecreasedTotalSupply(_vault, _amount, _delegateAmount);
}
// Conditionally emit the observation recorded event
if (_isObservationRecorded) {
emit TotalSupplyObservationRecorded(
_vault,
accountDetails.balance,
accountDetails.delegateBalance,
_isNewObservation,
_observation
);
}
}
/**
* @notice Increases the totalSupply balance and delegateBalance for a specific vault.
* @param _vault the vault for which the totalSupply balance is being increased
* @param _amount the amount of balance being increased
* @param _delegateAmount the amount of delegateBalance being increased
*/
function _increaseTotalSupplyBalances(
address _vault,
uint96 _amount,
uint96 _delegateAmount
) internal {
TwabLib.Account storage _account = totalSupplyObservations[_vault];
(
ObservationLib.Observation memory _observation,
bool _isNewObservation,
bool _isObservationRecorded,
TwabLib.AccountDetails memory accountDetails
) = TwabLib.increaseBalances(PERIOD_LENGTH, PERIOD_OFFSET, _account, _amount, _delegateAmount);
// Always emit the balance change event
if (_amount != 0 || _delegateAmount != 0) {
emit IncreasedTotalSupply(_vault, _amount, _delegateAmount);
}
// Conditionally emit the observation recorded event
if (_isObservationRecorded) {
emit TotalSupplyObservationRecorded(
_vault,
accountDetails.balance,
accountDetails.delegateBalance,
_isNewObservation,
_observation
);
}
}
}