generated from ZeframLou/foundry-template
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Gate.sol
1418 lines (1260 loc) · 54.2 KB
/
Gate.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.13;
import {BoringOwnable} from "boringsolidity/BoringOwnable.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {ERC4626} from "solmate/mixins/ERC4626.sol";
import {ReentrancyGuard} from "solmate/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";
import {Factory} from "./Factory.sol";
import {IxPYT} from "./external/IxPYT.sol";
import {FullMath} from "./lib/FullMath.sol";
import {Multicall} from "./lib/Multicall.sol";
import {SelfPermit} from "./lib/SelfPermit.sol";
import {NegativeYieldToken} from "./NegativeYieldToken.sol";
import {PerpetualYieldToken} from "./PerpetualYieldToken.sol";
/// @title Gate
/// @author zefram.eth
/// @notice Gate is the main contract users interact with to mint/burn NegativeYieldToken
/// and PerpetualYieldToken, as well as claim the yield earned by PYTs.
/// @dev Gate is an abstract contract that should be inherited from in order to support
/// a specific vault protocol (e.g. YearnGate supports YearnVault). Each Gate handles
/// all vaults & associated NYTs/PYTs of a specific vault protocol.
///
/// Vaults are yield-generating contracts used by Gate. Gate makes several assumptions about
/// a vault:
/// 1) A vault has a single associated underlying token that is immutable.
/// 2) A vault gives depositors yield denominated in the underlying token.
/// 3) A vault depositor owns shares in the vault, which represents their deposit.
/// 4) Vaults have a notion of "price per share", which is the amount of underlying tokens
/// each vault share can be redeemed for.
/// 5) If vault shares are represented using an ERC20 token, then the ERC20 token contract must be
/// the vault contract itself.
abstract contract Gate is
ReentrancyGuard,
Multicall,
SelfPermit,
BoringOwnable
{
/// -----------------------------------------------------------------------
/// Library usage
/// -----------------------------------------------------------------------
using SafeTransferLib for ERC20;
using SafeTransferLib for ERC4626;
/// -----------------------------------------------------------------------
/// Errors
/// -----------------------------------------------------------------------
error Error_InvalidInput();
error Error_VaultSharesNotERC20();
error Error_TokenPairNotDeployed();
error Error_EmergencyExitNotActivated();
error Error_SenderNotPerpetualYieldToken();
error Error_EmergencyExitAlreadyActivated();
/// -----------------------------------------------------------------------
/// Events
/// -----------------------------------------------------------------------
event EnterWithUnderlying(
address sender,
address indexed nytRecipient,
address indexed pytRecipient,
address indexed vault,
IxPYT xPYT,
uint256 underlyingAmount
);
event EnterWithVaultShares(
address sender,
address indexed nytRecipient,
address indexed pytRecipient,
address indexed vault,
IxPYT xPYT,
uint256 vaultSharesAmount
);
event ExitToUnderlying(
address indexed sender,
address indexed recipient,
address indexed vault,
IxPYT xPYT,
uint256 underlyingAmount
);
event ExitToVaultShares(
address indexed sender,
address indexed recipient,
address indexed vault,
IxPYT xPYT,
uint256 vaultSharesAmount
);
event ClaimYieldInUnderlying(
address indexed sender,
address indexed recipient,
address indexed vault,
uint256 underlyingAmount
);
event ClaimYieldInVaultShares(
address indexed sender,
address indexed recipient,
address indexed vault,
uint256 vaultSharesAmount
);
event ClaimYieldAndEnter(
address sender,
address indexed nytRecipient,
address indexed pytRecipient,
address indexed vault,
IxPYT xPYT,
uint256 amount
);
/// -----------------------------------------------------------------------
/// Structs
/// -----------------------------------------------------------------------
/// @param activated True if emergency exit has been activated, false if not
/// @param pytPriceInUnderlying The amount of underlying assets each PYT can redeem for.
/// Should be a value in the range [0, PRECISION]
struct EmergencyExitStatus {
bool activated;
uint96 pytPriceInUnderlying;
}
/// -----------------------------------------------------------------------
/// Constants
/// -----------------------------------------------------------------------
/// @notice The decimals of precision used by yieldPerTokenStored and pricePerVaultShareStored
uint256 internal constant PRECISION_DECIMALS = 27;
/// @notice The precision used by yieldPerTokenStored and pricePerVaultShareStored
uint256 internal constant PRECISION = 10**PRECISION_DECIMALS;
/// -----------------------------------------------------------------------
/// Immutable parameters
/// -----------------------------------------------------------------------
Factory public immutable factory;
/// -----------------------------------------------------------------------
/// Storage variables
/// -----------------------------------------------------------------------
/// @notice The amount of underlying tokens each vault share is worth, at the time of the last update.
/// Uses PRECISION.
/// @dev vault => value
mapping(address => uint256) public pricePerVaultShareStored;
/// @notice The amount of yield each PYT has accrued, at the time of the last update.
/// Scaled by PRECISION.
/// @dev vault => value
mapping(address => uint256) public yieldPerTokenStored;
/// @notice The amount of yield each PYT has accrued, at the time when a user has last interacted
/// with the gate/PYT. Shifted by 1, so e.g. 3 represents 2, 10 represents 9.
/// @dev vault => user => value
/// The value is shifted to use 0 for representing uninitialized users.
mapping(address => mapping(address => uint256))
public userYieldPerTokenStored;
/// @notice The amount of yield a user has accrued, at the time when they last interacted
/// with the gate/PYT (without calling claimYieldInUnderlying()).
/// Shifted by 1, so e.g. 3 represents 2, 10 represents 9.
/// @dev vault => user => value
mapping(address => mapping(address => uint256)) public userAccruedYield;
/// @notice Stores info relevant to emergency exits of a vault.
/// @dev vault => value
mapping(address => EmergencyExitStatus) public emergencyExitStatusOfVault;
/// -----------------------------------------------------------------------
/// Initialization
/// -----------------------------------------------------------------------
constructor(Factory factory_) {
factory = factory_;
}
/// -----------------------------------------------------------------------
/// User actions
/// -----------------------------------------------------------------------
/// @notice Converts underlying tokens into NegativeYieldToken and PerpetualYieldToken.
/// The amount of NYT and PYT minted will be equal to the underlying token amount.
/// @dev The underlying tokens will be immediately deposited into the specified vault.
/// If the NYT and PYT for the specified vault haven't been deployed yet, this call will
/// deploy them before proceeding, which will increase the gas cost significantly.
/// @param nytRecipient The recipient of the minted NYT
/// @param pytRecipient The recipient of the minted PYT
/// @param vault The vault to mint NYT and PYT for
/// @param xPYT The xPYT contract to deposit the minted PYT into. Set to 0 to receive raw PYT instead.
/// @param underlyingAmount The amount of underlying tokens to use
/// @return mintAmount The amount of NYT and PYT minted (the amounts are equal)
function enterWithUnderlying(
address nytRecipient,
address pytRecipient,
address vault,
IxPYT xPYT,
uint256 underlyingAmount
) external virtual nonReentrant returns (uint256 mintAmount) {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
if (underlyingAmount == 0) {
return 0;
}
/// -----------------------------------------------------------------------
/// State updates & effects
/// -----------------------------------------------------------------------
// mint PYT and NYT
mintAmount = underlyingAmount;
_enter(
nytRecipient,
pytRecipient,
vault,
xPYT,
underlyingAmount,
getPricePerVaultShare(vault)
);
// transfer underlying from msg.sender to address(this)
ERC20 underlying = getUnderlyingOfVault(vault);
underlying.safeTransferFrom(
msg.sender,
address(this),
underlyingAmount
);
// deposit underlying into vault
_depositIntoVault(underlying, underlyingAmount, vault);
emit EnterWithUnderlying(
msg.sender,
nytRecipient,
pytRecipient,
vault,
xPYT,
underlyingAmount
);
}
/// @notice Converts vault share tokens into NegativeYieldToken and PerpetualYieldToken.
/// @dev Only available if vault shares are transferrable ERC20 tokens.
/// If the NYT and PYT for the specified vault haven't been deployed yet, this call will
/// deploy them before proceeding, which will increase the gas cost significantly.
/// @param nytRecipient The recipient of the minted NYT
/// @param pytRecipient The recipient of the minted PYT
/// @param vault The vault to mint NYT and PYT for
/// @param xPYT The xPYT contract to deposit the minted PYT into. Set to 0 to receive raw PYT instead.
/// @param vaultSharesAmount The amount of vault share tokens to use
/// @return mintAmount The amount of NYT and PYT minted (the amounts are equal)
function enterWithVaultShares(
address nytRecipient,
address pytRecipient,
address vault,
IxPYT xPYT,
uint256 vaultSharesAmount
) external virtual nonReentrant returns (uint256 mintAmount) {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
if (vaultSharesAmount == 0) {
return 0;
}
// only supported if vault shares are ERC20
if (!vaultSharesIsERC20()) {
revert Error_VaultSharesNotERC20();
}
/// -----------------------------------------------------------------------
/// State updates & effects
/// -----------------------------------------------------------------------
// mint PYT and NYT
uint256 updatedPricePerVaultShare = getPricePerVaultShare(vault);
mintAmount = _vaultSharesAmountToUnderlyingAmount(
vault,
vaultSharesAmount,
updatedPricePerVaultShare
);
_enter(
nytRecipient,
pytRecipient,
vault,
xPYT,
mintAmount,
updatedPricePerVaultShare
);
// transfer vault tokens from msg.sender to address(this)
ERC20(vault).safeTransferFrom(
msg.sender,
address(this),
vaultSharesAmount
);
emit EnterWithVaultShares(
msg.sender,
nytRecipient,
pytRecipient,
vault,
xPYT,
vaultSharesAmount
);
}
/// @notice Converts NegativeYieldToken and PerpetualYieldToken to underlying tokens.
/// The amount of NYT and PYT burned will be equal to the underlying token amount.
/// @dev The underlying tokens will be immediately withdrawn from the specified vault.
/// If the NYT and PYT for the specified vault haven't been deployed yet, this call will
/// revert.
/// @param recipient The recipient of the minted NYT and PYT
/// @param vault The vault to mint NYT and PYT for
/// @param xPYT The xPYT contract to use for burning PYT. Set to 0 to burn raw PYT instead.
/// @param underlyingAmount The amount of underlying tokens requested
/// @return burnAmount The amount of NYT and PYT burned (the amounts are equal)
function exitToUnderlying(
address recipient,
address vault,
IxPYT xPYT,
uint256 underlyingAmount
) external virtual nonReentrant returns (uint256 burnAmount) {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
if (underlyingAmount == 0) {
return 0;
}
/// -----------------------------------------------------------------------
/// State updates & effects
/// -----------------------------------------------------------------------
// burn PYT and NYT
uint256 updatedPricePerVaultShare = getPricePerVaultShare(vault);
burnAmount = underlyingAmount;
_exit(vault, xPYT, underlyingAmount, updatedPricePerVaultShare);
// withdraw underlying from vault to recipient
// don't check balance since user can just withdraw slightly less
// saves gas this way
underlyingAmount = _withdrawFromVault(
recipient,
vault,
underlyingAmount,
updatedPricePerVaultShare,
false
);
emit ExitToUnderlying(
msg.sender,
recipient,
vault,
xPYT,
underlyingAmount
);
}
/// @notice Converts NegativeYieldToken and PerpetualYieldToken to vault share tokens.
/// The amount of NYT and PYT burned will be equal to the underlying token amount.
/// @dev Only available if vault shares are transferrable ERC20 tokens.
/// If the NYT and PYT for the specified vault haven't been deployed yet, this call will
/// revert.
/// @param recipient The recipient of the minted NYT and PYT
/// @param vault The vault to mint NYT and PYT for
/// @param xPYT The xPYT contract to use for burning PYT. Set to 0 to burn raw PYT instead.
/// @param vaultSharesAmount The amount of vault share tokens requested
/// @return burnAmount The amount of NYT and PYT burned (the amounts are equal)
function exitToVaultShares(
address recipient,
address vault,
IxPYT xPYT,
uint256 vaultSharesAmount
) external virtual nonReentrant returns (uint256 burnAmount) {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
if (vaultSharesAmount == 0) {
return 0;
}
// only supported if vault shares are ERC20
if (!vaultSharesIsERC20()) {
revert Error_VaultSharesNotERC20();
}
/// -----------------------------------------------------------------------
/// State updates & effects
/// -----------------------------------------------------------------------
// burn PYT and NYT
uint256 updatedPricePerVaultShare = getPricePerVaultShare(vault);
burnAmount = _vaultSharesAmountToUnderlyingAmountRoundingUp(
vault,
vaultSharesAmount,
updatedPricePerVaultShare
);
_exit(vault, xPYT, burnAmount, updatedPricePerVaultShare);
// transfer vault tokens to recipient
ERC20(vault).safeTransfer(recipient, vaultSharesAmount);
emit ExitToVaultShares(
msg.sender,
recipient,
vault,
xPYT,
vaultSharesAmount
);
}
/// @notice Claims the yield earned by the PerpetualYieldToken balance of msg.sender, in the underlying token.
/// @dev If the NYT and PYT for the specified vault haven't been deployed yet, this call will
/// revert.
/// @param recipient The recipient of the yield
/// @param vault The vault to claim yield from
/// @return yieldAmount The amount of yield claimed, in underlying tokens
function claimYieldInUnderlying(address recipient, address vault)
external
virtual
nonReentrant
returns (uint256 yieldAmount)
{
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update storage variables and compute yield amount
uint256 updatedPricePerVaultShare = getPricePerVaultShare(vault);
yieldAmount = _claimYield(vault, updatedPricePerVaultShare);
// withdraw yield
if (yieldAmount != 0) {
/// -----------------------------------------------------------------------
/// Effects
/// -----------------------------------------------------------------------
(uint8 fee, address protocolFeeRecipient) = factory
.protocolFeeInfo();
if (fee != 0) {
uint256 protocolFee = (yieldAmount * fee) / 1000;
unchecked {
// can't underflow since fee < 256
yieldAmount -= protocolFee;
}
if (vaultSharesIsERC20()) {
// vault shares are in ERC20
// do share transfer
protocolFee = _underlyingAmountToVaultSharesAmount(
vault,
protocolFee,
updatedPricePerVaultShare
);
uint256 vaultSharesBalance = ERC20(vault).balanceOf(
address(this)
);
if (protocolFee > vaultSharesBalance) {
protocolFee = vaultSharesBalance;
}
if (protocolFee != 0) {
ERC20(vault).safeTransfer(
protocolFeeRecipient,
protocolFee
);
}
} else {
// vault shares are not in ERC20
// withdraw underlying from vault
// checkBalance is set to true to prevent getting stuck
// due to rounding errors
if (protocolFee != 0) {
_withdrawFromVault(
protocolFeeRecipient,
vault,
protocolFee,
updatedPricePerVaultShare,
true
);
}
}
}
// withdraw underlying to recipient
// checkBalance is set to true to prevent getting stuck
// due to rounding errors
yieldAmount = _withdrawFromVault(
recipient,
vault,
yieldAmount,
updatedPricePerVaultShare,
true
);
emit ClaimYieldInUnderlying(
msg.sender,
recipient,
vault,
yieldAmount
);
}
}
/// @notice Claims the yield earned by the PerpetualYieldToken balance of msg.sender, in vault shares.
/// @dev Only available if vault shares are transferrable ERC20 tokens.
/// If the NYT and PYT for the specified vault haven't been deployed yet, this call will
/// revert.
/// @param recipient The recipient of the yield
/// @param vault The vault to claim yield from
/// @return yieldAmount The amount of yield claimed, in vault shares
function claimYieldInVaultShares(address recipient, address vault)
external
virtual
nonReentrant
returns (uint256 yieldAmount)
{
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
// only supported if vault shares are ERC20
if (!vaultSharesIsERC20()) {
revert Error_VaultSharesNotERC20();
}
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// update storage variables and compute yield amount
uint256 updatedPricePerVaultShare = getPricePerVaultShare(vault);
yieldAmount = _claimYield(vault, updatedPricePerVaultShare);
// withdraw yield
if (yieldAmount != 0) {
/// -----------------------------------------------------------------------
/// Effects
/// -----------------------------------------------------------------------
// convert yieldAmount to be denominated in vault shares
yieldAmount = _underlyingAmountToVaultSharesAmount(
vault,
yieldAmount,
updatedPricePerVaultShare
);
(uint8 fee, address protocolFeeRecipient) = factory
.protocolFeeInfo();
uint256 vaultSharesBalance = getVaultShareBalance(vault);
if (fee != 0) {
uint256 protocolFee = (yieldAmount * fee) / 1000;
protocolFee = protocolFee > vaultSharesBalance
? vaultSharesBalance
: protocolFee;
unchecked {
// can't underflow since fee < 256
yieldAmount -= protocolFee;
}
if (protocolFee > 0) {
ERC20(vault).safeTransfer(
protocolFeeRecipient,
protocolFee
);
vaultSharesBalance -= protocolFee;
}
}
// transfer vault shares to recipient
// check if vault shares is enough to prevent getting stuck
// from rounding errors
yieldAmount = yieldAmount > vaultSharesBalance
? vaultSharesBalance
: yieldAmount;
if (yieldAmount > 0) {
ERC20(vault).safeTransfer(recipient, yieldAmount);
}
emit ClaimYieldInVaultShares(
msg.sender,
recipient,
vault,
yieldAmount
);
}
}
/// @notice Claims the yield earned by the PerpetualYieldToken balance of msg.sender, and immediately
/// use the yield to mint NYT and PYT.
/// @dev Introduced to save gas for xPYT compounding, since it avoids vault withdraws/transfers.
/// If the NYT and PYT for the specified vault haven't been deployed yet, this call will
/// revert.
/// @param nytRecipient The recipient of the minted NYT
/// @param pytRecipient The recipient of the minted PYT
/// @param vault The vault to claim yield from
/// @param xPYT The xPYT contract to deposit the minted PYT into. Set to 0 to receive raw PYT instead.
/// @return yieldAmount The amount of yield claimed, in underlying tokens
function claimYieldAndEnter(
address nytRecipient,
address pytRecipient,
address vault,
IxPYT xPYT
) external virtual nonReentrant returns (uint256 yieldAmount) {
// update storage variables and compute yield amount
uint256 updatedPricePerVaultShare = getPricePerVaultShare(vault);
yieldAmount = _claimYield(vault, updatedPricePerVaultShare);
// use yield to mint NYT and PYT
if (yieldAmount != 0) {
(uint8 fee, address protocolFeeRecipient) = factory
.protocolFeeInfo();
if (fee != 0) {
uint256 protocolFee = (yieldAmount * fee) / 1000;
unchecked {
// can't underflow since fee < 256
yieldAmount -= protocolFee;
}
if (vaultSharesIsERC20()) {
// vault shares are in ERC20
// do share transfer
protocolFee = _underlyingAmountToVaultSharesAmount(
vault,
protocolFee,
updatedPricePerVaultShare
);
uint256 vaultSharesBalance = ERC20(vault).balanceOf(
address(this)
);
if (protocolFee > vaultSharesBalance) {
protocolFee = vaultSharesBalance;
}
if (protocolFee != 0) {
ERC20(vault).safeTransfer(
protocolFeeRecipient,
protocolFee
);
}
} else {
// vault shares are not in ERC20
// withdraw underlying from vault
// checkBalance is set to true to prevent getting stuck
// due to rounding errors
if (protocolFee != 0) {
_withdrawFromVault(
protocolFeeRecipient,
vault,
protocolFee,
updatedPricePerVaultShare,
true
);
}
}
}
NegativeYieldToken nyt = getNegativeYieldTokenForVault(vault);
PerpetualYieldToken pyt = getPerpetualYieldTokenForVault(vault);
if (address(xPYT) == address(0)) {
// accrue yield to pytRecipient if they're not msg.sender
// no need to do it if the recipient is msg.sender, since
// we already accrued yield in _claimYield
if (pytRecipient != msg.sender) {
_accrueYield(
vault,
pyt,
pytRecipient,
updatedPricePerVaultShare
);
}
} else {
// accrue yield to xPYT contract since it gets minted PYT
_accrueYield(
vault,
pyt,
address(xPYT),
updatedPricePerVaultShare
);
}
// mint NYTs and PYTs
nyt.gateMint(nytRecipient, yieldAmount);
if (address(xPYT) == address(0)) {
// mint raw PYT to recipient
pyt.gateMint(pytRecipient, yieldAmount);
} else {
// mint PYT to xPYT contract
pyt.gateMint(address(xPYT), yieldAmount);
/// -----------------------------------------------------------------------
/// Effects
/// -----------------------------------------------------------------------
// call sweep to mint xPYT using the PYT
xPYT.sweep(pytRecipient);
}
emit ClaimYieldAndEnter(
msg.sender,
nytRecipient,
pytRecipient,
vault,
xPYT,
yieldAmount
);
}
}
/// -----------------------------------------------------------------------
/// Getters
/// -----------------------------------------------------------------------
/// @notice Returns the NegativeYieldToken associated with a vault.
/// @dev Returns non-zero value even if the contract hasn't been deployed yet.
/// @param vault The vault to query
/// @return The NegativeYieldToken address
function getNegativeYieldTokenForVault(address vault)
public
view
virtual
returns (NegativeYieldToken)
{
return factory.getNegativeYieldToken(this, vault);
}
/// @notice Returns the PerpetualYieldToken associated with a vault.
/// @dev Returns non-zero value even if the contract hasn't been deployed yet.
/// @param vault The vault to query
/// @return The PerpetualYieldToken address
function getPerpetualYieldTokenForVault(address vault)
public
view
virtual
returns (PerpetualYieldToken)
{
return factory.getPerpetualYieldToken(this, vault);
}
/// @notice Returns the amount of yield claimable by a PerpetualYieldToken holder from a vault.
/// Accounts for protocol fees.
/// @param vault The vault to query
/// @param user The PYT holder to query
/// @return yieldAmount The amount of yield claimable
function getClaimableYieldAmount(address vault, address user)
external
view
virtual
returns (uint256 yieldAmount)
{
PerpetualYieldToken pyt = getPerpetualYieldTokenForVault(vault);
uint256 userYieldPerTokenStored_ = userYieldPerTokenStored[vault][user];
if (userYieldPerTokenStored_ == 0) {
// uninitialized account
return 0;
}
yieldAmount = _getClaimableYieldAmount(
vault,
user,
_computeYieldPerToken(vault, pyt, getPricePerVaultShare(vault)),
userYieldPerTokenStored_,
pyt.balanceOf(user)
);
(uint8 fee, ) = factory.protocolFeeInfo();
if (fee != 0) {
uint256 protocolFee = (yieldAmount * fee) / 1000;
unchecked {
// can't underflow since fee < 256
yieldAmount -= protocolFee;
}
}
}
/// @notice Computes the latest yieldPerToken value for a vault.
/// @param vault The vault to query
/// @return The latest yieldPerToken value
function computeYieldPerToken(address vault)
external
view
virtual
returns (uint256)
{
return
_computeYieldPerToken(
vault,
getPerpetualYieldTokenForVault(vault),
getPricePerVaultShare(vault)
);
}
/// @notice Returns the underlying token of a vault.
/// @param vault The vault to query
/// @return The underlying token
function getUnderlyingOfVault(address vault)
public
view
virtual
returns (ERC20);
/// @notice Returns the amount of underlying tokens each share of a vault is worth.
/// @param vault The vault to query
/// @return The pricePerVaultShare value
function getPricePerVaultShare(address vault)
public
view
virtual
returns (uint256);
/// @notice Returns the amount of vault shares owned by the gate.
/// @param vault The vault to query
/// @return The gate's vault share balance
function getVaultShareBalance(address vault)
public
view
virtual
returns (uint256);
/// @return True if the vaults supported by this gate use transferrable ERC20 tokens
/// to represent shares, false otherwise.
function vaultSharesIsERC20() public pure virtual returns (bool);
/// @notice Computes the ERC20 name of the NegativeYieldToken of a vault.
/// @param vault The vault to query
/// @return The ERC20 name
function negativeYieldTokenName(address vault)
external
view
virtual
returns (string memory);
/// @notice Computes the ERC20 symbol of the NegativeYieldToken of a vault.
/// @param vault The vault to query
/// @return The ERC20 symbol
function negativeYieldTokenSymbol(address vault)
external
view
virtual
returns (string memory);
/// @notice Computes the ERC20 name of the PerpetualYieldToken of a vault.
/// @param vault The vault to query
/// @return The ERC20 name
function perpetualYieldTokenName(address vault)
external
view
virtual
returns (string memory);
/// @notice Computes the ERC20 symbol of the NegativeYieldToken of a vault.
/// @param vault The vault to query
/// @return The ERC20 symbol
function perpetualYieldTokenSymbol(address vault)
external
view
virtual
returns (string memory);
/// -----------------------------------------------------------------------
/// PYT transfer hook
/// -----------------------------------------------------------------------
/// @notice SHOULD NOT BE CALLED BY USERS, ONLY CALLED BY PERPETUAL YIELD TOKEN CONTRACTS
/// @dev Called by PYT contracts deployed by this gate before each token transfer, in order to
/// accrue the yield earned by the from & to accounts
/// @param from The token transfer from account
/// @param to The token transfer to account
/// @param fromBalance The token balance of the from account before the transfer
/// @param toBalance The token balance of the to account before the transfer
function beforePerpetualYieldTokenTransfer(
address from,
address to,
uint256 amount,
uint256 fromBalance,
uint256 toBalance
) external virtual {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
if (amount == 0) {
return;
}
address vault = PerpetualYieldToken(msg.sender).vault();
PerpetualYieldToken pyt = getPerpetualYieldTokenForVault(vault);
if (msg.sender != address(pyt)) {
revert Error_SenderNotPerpetualYieldToken();
}
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// accrue yield
uint256 updatedPricePerVaultShare = getPricePerVaultShare(vault);
uint256 updatedYieldPerToken = _computeYieldPerToken(
vault,
pyt,
updatedPricePerVaultShare
);
yieldPerTokenStored[vault] = updatedYieldPerToken;
pricePerVaultShareStored[vault] = updatedPricePerVaultShare;
// we know the from account must have held PYTs before
// so we will always accrue the yield earned by the from account
userAccruedYield[vault][from] =
_getClaimableYieldAmount(
vault,
from,
updatedYieldPerToken,
userYieldPerTokenStored[vault][from],
fromBalance
) +
1;
userYieldPerTokenStored[vault][from] = updatedYieldPerToken + 1;
// the to account might not have held PYTs before
// we only accrue yield if they have
uint256 toUserYieldPerTokenStored = userYieldPerTokenStored[vault][to];
if (toUserYieldPerTokenStored != 0) {
// to account has held PYTs before
userAccruedYield[vault][to] =
_getClaimableYieldAmount(
vault,
to,
updatedYieldPerToken,
toUserYieldPerTokenStored,
toBalance
) +
1;
}
userYieldPerTokenStored[vault][to] = updatedYieldPerToken + 1;
}
/// -----------------------------------------------------------------------
/// Emergency exit
/// -----------------------------------------------------------------------
/// @notice Activates the emergency exit mode for a certain vault. Only callable by owner.
/// @dev Activating emergency exit allows PYT/NYT holders to do single-sided burns to redeem the underlying
/// collateral. This is to prevent cases where a large portion of PYT/NYT is locked up in a buggy/malicious contract
/// and locks up the underlying collateral forever.
/// @param vault The vault to activate emergency exit for
/// @param pytPriceInUnderlying The amount of underlying asset burning each PYT can redeem. Scaled by PRECISION.
function ownerActivateEmergencyExitForVault(
address vault,
uint96 pytPriceInUnderlying
) external virtual onlyOwner {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
// we only allow emergency exit to be activated once (until deactivation)
// because if pytPriceInUnderlying is ever modified after activation
// then PYT/NYT will become unbacked
if (emergencyExitStatusOfVault[vault].activated) {
revert Error_EmergencyExitAlreadyActivated();
}
// we need to ensure the PYT price value is within the range [0, PRECISION]
if (pytPriceInUnderlying > PRECISION) {
revert Error_InvalidInput();
}
// the PYT & NYT must have already been deployed
NegativeYieldToken nyt = getNegativeYieldTokenForVault(vault);
if (address(nyt).code.length == 0) {
revert Error_TokenPairNotDeployed();
}
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
emergencyExitStatusOfVault[vault] = EmergencyExitStatus({
activated: true,
pytPriceInUnderlying: pytPriceInUnderlying
});
}
/// @notice Deactivates the emergency exit mode for a certain vault. Only callable by owner.
/// @param vault The vault to deactivate emergency exit for
function ownerDeactivateEmergencyExitForVault(address vault)
external
virtual
onlyOwner
{
/// -----------------------------------------------------------------------