-
Notifications
You must be signed in to change notification settings - Fork 318
/
Vault.vy
1838 lines (1527 loc) · 67.3 KB
/
Vault.vy
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
# @version 0.3.3
"""
@title Yearn Token Vault
@license GNU AGPLv3
@author yearn.finance
@notice
Yearn Token Vault. Holds an underlying token, and allows users to interact
with the Yearn ecosystem through Strategies connected to the Vault.
Vaults are not limited to a single Strategy, they can have as many Strategies
as can be designed (however the withdrawal queue is capped at 20.)
Deposited funds are moved into the most impactful strategy that has not
already reached its limit for assets under management, regardless of which
Strategy a user's funds end up in, they receive their portion of yields
generated across all Strategies.
When a user withdraws, if there are no funds sitting undeployed in the
Vault, the Vault withdraws funds from Strategies in the order of least
impact. (Funds are taken from the Strategy that will disturb everyone's
gains the least, then the next least, etc.) In order to achieve this, the
withdrawal queue's order must be properly set and managed by the community
(through governance).
Vault Strategies are parameterized to pursue the highest risk-adjusted yield.
There is an "Emergency Shutdown" mode. When the Vault is put into emergency
shutdown, assets will be recalled from the Strategies as quickly as is
practical (given on-chain conditions), minimizing loss. Deposits are
halted, new Strategies may not be added, and each Strategy exits with the
minimum possible damage to position, while opening up deposits to be
withdrawn by users. There are no restrictions on withdrawals above what is
expected under Normal Operation.
For further details, please refer to the specification:
https://github.com/iearn-finance/yearn-vaults/blob/main/SPECIFICATION.md
"""
API_VERSION: constant(String[28]) = "0.4.6"
from vyper.interfaces import ERC20
implements: ERC20
interface DetailedERC20:
def name() -> String[42]: view
def symbol() -> String[20]: view
def decimals() -> uint256: view
interface Strategy:
def want() -> address: view
def vault() -> address: view
def isActive() -> bool: view
def delegatedAssets() -> uint256: view
def estimatedTotalAssets() -> uint256: view
def withdraw(_amount: uint256) -> uint256: nonpayable
def migrate(_newStrategy: address): nonpayable
def emergencyExit() -> bool: view
name: public(String[64])
symbol: public(String[32])
decimals: public(uint256)
balanceOf: public(HashMap[address, uint256])
allowance: public(HashMap[address, HashMap[address, uint256]])
totalSupply: public(uint256)
token: public(ERC20)
governance: public(address)
management: public(address)
guardian: public(address)
pendingGovernance: address
struct StrategyParams:
performanceFee: uint256 # Strategist's fee (basis points)
activation: uint256 # Activation block.timestamp
debtRatio: uint256 # Maximum borrow amount (in BPS of total assets)
minDebtPerHarvest: uint256 # Lower limit on the increase of debt since last harvest
maxDebtPerHarvest: uint256 # Upper limit on the increase of debt since last harvest
lastReport: uint256 # block.timestamp of the last time a report occured
totalDebt: uint256 # Total outstanding debt that Strategy has
totalGain: uint256 # Total returns that Strategy has realized for Vault
totalLoss: uint256 # Total losses that Strategy has realized for Vault
event Transfer:
sender: indexed(address)
receiver: indexed(address)
value: uint256
event Approval:
owner: indexed(address)
spender: indexed(address)
value: uint256
event Deposit:
recipient: indexed(address)
shares: uint256
amount: uint256
event Withdraw:
recipient: indexed(address)
shares: uint256
amount: uint256
event Sweep:
token: indexed(address)
amount: uint256
event LockedProfitDegradationUpdated:
value: uint256
event StrategyAdded:
strategy: indexed(address)
debtRatio: uint256 # Maximum borrow amount (in BPS of total assets)
minDebtPerHarvest: uint256 # Lower limit on the increase of debt since last harvest
maxDebtPerHarvest: uint256 # Upper limit on the increase of debt since last harvest
performanceFee: uint256 # Strategist's fee (basis points)
event StrategyReported:
strategy: indexed(address)
gain: uint256
loss: uint256
debtPaid: uint256
totalGain: uint256
totalLoss: uint256
totalDebt: uint256
debtAdded: uint256
debtRatio: uint256
event FeeReport:
management_fee: uint256
performance_fee: uint256
strategist_fee: uint256
duration: uint256
event WithdrawFromStrategy:
strategy: indexed(address)
totalDebt: uint256
loss: uint256
event UpdateGovernance:
governance: address # New active governance
event UpdateManagement:
management: address # New active manager
event UpdateRewards:
rewards: address # New active rewards recipient
event UpdateDepositLimit:
depositLimit: uint256 # New active deposit limit
event UpdatePerformanceFee:
performanceFee: uint256 # New active performance fee
event UpdateManagementFee:
managementFee: uint256 # New active management fee
event UpdateGuardian:
guardian: address # Address of the active guardian
event EmergencyShutdown:
active: bool # New emergency shutdown state (if false, normal operation enabled)
event UpdateWithdrawalQueue:
queue: address[MAXIMUM_STRATEGIES] # New active withdrawal queue
event StrategyUpdateDebtRatio:
strategy: indexed(address) # Address of the strategy for the debt ratio adjustment
debtRatio: uint256 # The new debt limit for the strategy (in BPS of total assets)
event StrategyUpdateMinDebtPerHarvest:
strategy: indexed(address) # Address of the strategy for the rate limit adjustment
minDebtPerHarvest: uint256 # Lower limit on the increase of debt since last harvest
event StrategyUpdateMaxDebtPerHarvest:
strategy: indexed(address) # Address of the strategy for the rate limit adjustment
maxDebtPerHarvest: uint256 # Upper limit on the increase of debt since last harvest
event StrategyUpdatePerformanceFee:
strategy: indexed(address) # Address of the strategy for the performance fee adjustment
performanceFee: uint256 # The new performance fee for the strategy
event StrategyMigrated:
oldVersion: indexed(address) # Old version of the strategy to be migrated
newVersion: indexed(address) # New version of the strategy
event StrategyRevoked:
strategy: indexed(address) # Address of the strategy that is revoked
event StrategyRemovedFromQueue:
strategy: indexed(address) # Address of the strategy that is removed from the withdrawal queue
event StrategyAddedToQueue:
strategy: indexed(address) # Address of the strategy that is added to the withdrawal queue
event NewPendingGovernance:
pendingGovernance: indexed(address)
# NOTE: Track the total for overhead targeting purposes
strategies: public(HashMap[address, StrategyParams])
MAXIMUM_STRATEGIES: constant(uint256) = 20
DEGRADATION_COEFFICIENT: constant(uint256) = 10 ** 18
# Ordering that `withdraw` uses to determine which strategies to pull funds from
# NOTE: Does *NOT* have to match the ordering of all the current strategies that
# exist, but it is recommended that it does or else withdrawal depth is
# limited to only those inside the queue.
# NOTE: Ordering is determined by governance, and should be balanced according
# to risk, slippage, and/or volatility. Can also be ordered to increase the
# withdrawal speed of a particular Strategy.
# NOTE: The first time a ZERO_ADDRESS is encountered, it stops withdrawing
withdrawalQueue: public(address[MAXIMUM_STRATEGIES])
emergencyShutdown: public(bool)
depositLimit: public(uint256) # Limit for totalAssets the Vault can hold
debtRatio: public(uint256) # Debt ratio for the Vault across all strategies (in BPS, <= 10k)
totalIdle: public(uint256) # Amount of tokens that are in the vault
totalDebt: public(uint256) # Amount of tokens that all strategies have borrowed
lastReport: public(uint256) # block.timestamp of last report
activation: public(uint256) # block.timestamp of contract deployment
lockedProfit: public(uint256) # how much profit is locked and cant be withdrawn
lockedProfitDegradation: public(uint256) # rate per block of degradation. DEGRADATION_COEFFICIENT is 100% per block
rewards: public(address) # Rewards contract where Governance fees are sent to
# Governance Fee for management of Vault (given to `rewards`)
managementFee: public(uint256)
# Governance Fee for performance of Vault (given to `rewards`)
performanceFee: public(uint256)
MAX_BPS: constant(uint256) = 10_000 # 100%, or 10k basis points
# NOTE: A four-century period will be missing 3 of its 100 Julian leap years, leaving 97.
# So the average year has 365 + 97/400 = 365.2425 days
# ERROR(Julian): -0.0078
# ERROR(Gregorian): -0.0003
# A day = 24 * 60 * 60 sec = 86400 sec
# 365.2425 * 86400 = 31556952.0
SECS_PER_YEAR: constant(uint256) = 31_556_952 # 365.2425 days
# `nonces` track `permit` approvals with signature.
nonces: public(HashMap[address, uint256])
DOMAIN_TYPE_HASH: constant(bytes32) = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
PERMIT_TYPE_HASH: constant(bytes32) = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
@external
def initialize(
token: address,
governance: address,
rewards: address,
nameOverride: String[64],
symbolOverride: String[32],
guardian: address = msg.sender,
management: address = msg.sender,
):
"""
@notice
Initializes the Vault, this is called only once, when the contract is
deployed.
The performance fee is set to 10% of yield, per Strategy.
The management fee is set to 2%, per year.
The initial deposit limit is set to 0 (deposits disabled); it must be
updated after initialization.
@dev
If `nameOverride` is not specified, the name will be 'yearn'
combined with the name of `token`.
If `symbolOverride` is not specified, the symbol will be 'yv'
combined with the symbol of `token`.
The token used by the vault should not change balances outside transfers and
it must transfer the exact amount requested. Fee on transfer and rebasing are not supported.
@param token The token that may be deposited into this Vault.
@param governance The address authorized for governance interactions.
@param rewards The address to distribute rewards to.
@param management The address of the vault manager.
@param nameOverride Specify a custom Vault name. Leave empty for default choice.
@param symbolOverride Specify a custom Vault symbol name. Leave empty for default choice.
@param guardian The address authorized for guardian interactions. Defaults to caller.
"""
assert self.activation == 0 # dev: no devops199
self.token = ERC20(token)
if nameOverride == "":
self.name = concat(DetailedERC20(token).symbol(), " yVault")
else:
self.name = nameOverride
if symbolOverride == "":
self.symbol = concat("yv", DetailedERC20(token).symbol())
else:
self.symbol = symbolOverride
decimals: uint256 = DetailedERC20(token).decimals()
self.decimals = decimals
assert decimals < 256 # dev: see VVE-2020-0001
self.governance = governance
log UpdateGovernance(governance)
self.management = management
log UpdateManagement(management)
self.rewards = rewards
log UpdateRewards(rewards)
self.guardian = guardian
log UpdateGuardian(guardian)
self.performanceFee = 1000 # 10% of yield (per Strategy)
log UpdatePerformanceFee(convert(1000, uint256))
self.managementFee = 200 # 2% per year
log UpdateManagementFee(convert(200, uint256))
self.lastReport = block.timestamp
self.activation = block.timestamp
self.lockedProfitDegradation = convert(DEGRADATION_COEFFICIENT * 46 / 10 ** 6 , uint256) # 6 hours in blocks
# EIP-712
@pure
@external
def apiVersion() -> String[28]:
"""
@notice
Used to track the deployed version of this contract. In practice you
can use this version number to compare with Yearn's GitHub and
determine which version of the source matches this deployed contract.
@dev
All strategies must have an `apiVersion()` that matches the Vault's
`API_VERSION`.
@return API_VERSION which holds the current version of this contract.
"""
return API_VERSION
@view
@internal
def domain_separator() -> bytes32:
return keccak256(
concat(
DOMAIN_TYPE_HASH,
keccak256(convert("Yearn Vault", Bytes[11])),
keccak256(convert(API_VERSION, Bytes[28])),
convert(chain.id, bytes32),
convert(self, bytes32)
)
)
@view
@external
def DOMAIN_SEPARATOR() -> bytes32:
return self.domain_separator()
@external
def setName(name: String[64]):
"""
@notice
Used to change the value of `name`.
This may only be called by governance.
@param name The new name to use.
"""
assert msg.sender == self.governance
self.name = name
@external
def setSymbol(symbol: String[32]):
"""
@notice
Used to change the value of `symbol`.
This may only be called by governance.
@param symbol The new symbol to use.
"""
assert msg.sender == self.governance
self.symbol = symbol
# 2-phase commit for a change in governance
@external
def setGovernance(governance: address):
"""
@notice
Nominate a new address to use as governance.
The change does not go into effect immediately. This function sets a
pending change, and the governance address is not updated until
the proposed governance address has accepted the responsibility.
This may only be called by the current governance address.
@param governance The address requested to take over Vault governance.
"""
assert msg.sender == self.governance
log NewPendingGovernance(governance)
self.pendingGovernance = governance
@external
def acceptGovernance():
"""
@notice
Once a new governance address has been proposed using setGovernance(),
this function may be called by the proposed address to accept the
responsibility of taking over governance for this contract.
This may only be called by the proposed governance address.
@dev
setGovernance() should be called by the existing governance address,
prior to calling this function.
"""
assert msg.sender == self.pendingGovernance
self.governance = msg.sender
log UpdateGovernance(msg.sender)
@external
def setManagement(management: address):
"""
@notice
Changes the management address.
Management is able to make some investment decisions adjusting parameters.
This may only be called by governance.
@param management The address to use for managing.
"""
assert msg.sender == self.governance
self.management = management
log UpdateManagement(management)
@external
def setRewards(rewards: address):
"""
@notice
Changes the rewards address. Any distributed rewards
will cease flowing to the old address and begin flowing
to this address once the change is in effect.
This will not change any Strategy reports in progress, only
new reports made after this change goes into effect.
This may only be called by governance.
@param rewards The address to use for collecting rewards.
"""
assert msg.sender == self.governance
assert not (rewards in [self, ZERO_ADDRESS])
self.rewards = rewards
log UpdateRewards(rewards)
@external
def setLockedProfitDegradation(degradation: uint256):
"""
@notice
Changes the locked profit degradation.
@param degradation The rate of degradation in percent per second scaled to 1e18.
"""
assert msg.sender == self.governance
# Since "degradation" is of type uint256 it can never be less than zero
assert degradation <= DEGRADATION_COEFFICIENT
self.lockedProfitDegradation = degradation
log LockedProfitDegradationUpdated(degradation)
@external
def setDepositLimit(limit: uint256):
"""
@notice
Changes the maximum amount of tokens that can be deposited in this Vault.
Note, this is not how much may be deposited by a single depositor,
but the maximum amount that may be deposited across all depositors.
This may only be called by governance.
@param limit The new deposit limit to use.
"""
assert msg.sender == self.governance
self.depositLimit = limit
log UpdateDepositLimit(limit)
@external
def setPerformanceFee(fee: uint256):
"""
@notice
Used to change the value of `performanceFee`.
Should set this value below the maximum strategist performance fee.
This may only be called by governance.
@param fee The new performance fee to use.
"""
assert msg.sender == self.governance
assert fee <= MAX_BPS / 2
self.performanceFee = fee
log UpdatePerformanceFee(fee)
@external
def setManagementFee(fee: uint256):
"""
@notice
Used to change the value of `managementFee`.
This may only be called by governance.
@param fee The new management fee to use.
"""
assert msg.sender == self.governance
assert fee <= MAX_BPS
self.managementFee = fee
log UpdateManagementFee(fee)
@external
def setGuardian(guardian: address):
"""
@notice
Used to change the address of `guardian`.
This may only be called by governance or the existing guardian.
@param guardian The new guardian address to use.
"""
assert msg.sender in [self.guardian, self.governance]
self.guardian = guardian
log UpdateGuardian(guardian)
@external
def setEmergencyShutdown(active: bool):
"""
@notice
Activates or deactivates Vault mode where all Strategies go into full
withdrawal.
During Emergency Shutdown:
1. No Users may deposit into the Vault (but may withdraw as usual.)
2. Governance may not add new Strategies.
3. Each Strategy must pay back their debt as quickly as reasonable to
minimally affect their position.
4. Only Governance may undo Emergency Shutdown.
See contract level note for further details.
This may only be called by governance or the guardian.
@param active
If true, the Vault goes into Emergency Shutdown. If false, the Vault
goes back into Normal Operation.
"""
if active:
assert msg.sender in [self.guardian, self.governance]
else:
assert msg.sender == self.governance
self.emergencyShutdown = active
log EmergencyShutdown(active)
@external
def setWithdrawalQueue(queue: address[MAXIMUM_STRATEGIES]):
"""
@notice
Updates the withdrawalQueue to match the addresses and order specified
by `queue`.
There can be fewer strategies than the maximum, as well as fewer than
the total number of strategies active in the vault. `withdrawalQueue`
will be updated in a gas-efficient manner, assuming the input is well-
ordered with 0x0 only at the end.
This may only be called by governance or management.
@dev
This is order sensitive, specify the addresses in the order in which
funds should be withdrawn (so `queue`[0] is the first Strategy withdrawn
from, `queue`[1] is the second, etc.)
This means that the least impactful Strategy (the Strategy that will have
its core positions impacted the least by having funds removed) should be
at `queue`[0], then the next least impactful at `queue`[1], and so on.
@param queue
The array of addresses to use as the new withdrawal queue. This is
order sensitive.
"""
assert msg.sender in [self.management, self.governance]
# HACK: Temporary until Vyper adds support for Dynamic arrays
old_queue: address[MAXIMUM_STRATEGIES] = empty(address[MAXIMUM_STRATEGIES])
for i in range(MAXIMUM_STRATEGIES):
old_queue[i] = self.withdrawalQueue[i]
if queue[i] == ZERO_ADDRESS:
# NOTE: Cannot use this method to remove entries from the queue
assert old_queue[i] == ZERO_ADDRESS
break
# NOTE: Cannot use this method to add more entries to the queue
assert old_queue[i] != ZERO_ADDRESS
assert self.strategies[queue[i]].activation > 0
existsInOldQueue: bool = False
for j in range(MAXIMUM_STRATEGIES):
if queue[j] == ZERO_ADDRESS:
existsInOldQueue = True
break
if queue[i] == old_queue[j]:
# NOTE: Ensure that every entry in queue prior to reordering exists now
existsInOldQueue = True
if j <= i:
# NOTE: This will only check for duplicate entries in queue after `i`
continue
assert queue[i] != queue[j] # dev: do not add duplicate strategies
assert existsInOldQueue # dev: do not add new strategies
self.withdrawalQueue[i] = queue[i]
log UpdateWithdrawalQueue(queue)
@internal
def erc20_safe_transfer(token: address, receiver: address, amount: uint256):
# Used only to send tokens that are not the type managed by this Vault.
# HACK: Used to handle non-compliant tokens like USDT
response: Bytes[32] = raw_call(
token,
concat(
method_id("transfer(address,uint256)"),
convert(receiver, bytes32),
convert(amount, bytes32),
),
max_outsize=32,
)
if len(response) > 0:
assert convert(response, bool), "Transfer failed!"
@internal
def erc20_safe_transferFrom(token: address, sender: address, receiver: address, amount: uint256):
# Used only to send tokens that are not the type managed by this Vault.
# HACK: Used to handle non-compliant tokens like USDT
response: Bytes[32] = raw_call(
token,
concat(
method_id("transferFrom(address,address,uint256)"),
convert(sender, bytes32),
convert(receiver, bytes32),
convert(amount, bytes32),
),
max_outsize=32,
)
if len(response) > 0:
assert convert(response, bool), "Transfer failed!"
@internal
def _transfer(sender: address, receiver: address, amount: uint256):
# See note on `transfer()`.
# Protect people from accidentally sending their shares to bad places
assert receiver not in [self, ZERO_ADDRESS]
self.balanceOf[sender] -= amount
self.balanceOf[receiver] += amount
log Transfer(sender, receiver, amount)
@external
def transfer(receiver: address, amount: uint256) -> bool:
"""
@notice
Transfers shares from the caller's address to `receiver`. This function
will always return true, unless the user is attempting to transfer
shares to this contract's address, or to 0x0.
@param receiver
The address shares are being transferred to. Must not be this contract's
address, must not be 0x0.
@param amount The quantity of shares to transfer.
@return
True if transfer is sent to an address other than this contract's or
0x0, otherwise the transaction will fail.
"""
self._transfer(msg.sender, receiver, amount)
return True
@external
def transferFrom(sender: address, receiver: address, amount: uint256) -> bool:
"""
@notice
Transfers `amount` shares from `sender` to `receiver`. This operation will
always return true, unless the user is attempting to transfer shares
to this contract's address, or to 0x0.
Unless the caller has given this contract unlimited approval,
transfering shares will decrement the caller's `allowance` by `amount`.
@param sender The address shares are being transferred from.
@param receiver
The address shares are being transferred to. Must not be this contract's
address, must not be 0x0.
@param amount The quantity of shares to transfer.
@return
True if transfer is sent to an address other than this contract's or
0x0, otherwise the transaction will fail.
"""
# Unlimited approval (saves an SSTORE)
if (self.allowance[sender][msg.sender] < MAX_UINT256):
allowance: uint256 = self.allowance[sender][msg.sender] - amount
self.allowance[sender][msg.sender] = allowance
# NOTE: Allows log filters to have a full accounting of allowance changes
log Approval(sender, msg.sender, allowance)
self._transfer(sender, receiver, amount)
return True
@external
def approve(spender: address, amount: uint256) -> bool:
"""
@dev Approve the passed address to spend the specified amount of tokens on behalf of
`msg.sender`. Beware that changing an allowance with this method brings the risk
that someone may use both the old and the new allowance by unfortunate transaction
ordering. See https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
@param spender The address which will spend the funds.
@param amount The amount of tokens to be spent.
"""
self.allowance[msg.sender][spender] = amount
log Approval(msg.sender, spender, amount)
return True
@external
def increaseAllowance(spender: address, amount: uint256) -> bool:
"""
@dev Increase the allowance of the passed address to spend the total amount of tokens
on behalf of msg.sender. This method mitigates the risk that someone may use both
the old and the new allowance by unfortunate transaction ordering.
See https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
@param spender The address which will spend the funds.
@param amount The amount of tokens to increase the allowance by.
"""
self.allowance[msg.sender][spender] += amount
log Approval(msg.sender, spender, self.allowance[msg.sender][spender])
return True
@external
def decreaseAllowance(spender: address, amount: uint256) -> bool:
"""
@dev Decrease the allowance of the passed address to spend the total amount of tokens
on behalf of msg.sender. This method mitigates the risk that someone may use both
the old and the new allowance by unfortunate transaction ordering.
See https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
@param spender The address which will spend the funds.
@param amount The amount of tokens to decrease the allowance by.
"""
self.allowance[msg.sender][spender] -= amount
log Approval(msg.sender, spender, self.allowance[msg.sender][spender])
return True
@external
def permit(owner: address, spender: address, amount: uint256, expiry: uint256, signature: Bytes[65]) -> bool:
"""
@notice
Approves spender by owner's signature to expend owner's tokens.
See https://eips.ethereum.org/EIPS/eip-2612.
@param owner The address which is a source of funds and has signed the Permit.
@param spender The address which is allowed to spend the funds.
@param amount The amount of tokens to be spent.
@param expiry The timestamp after which the Permit is no longer valid.
@param signature A valid secp256k1 signature of Permit by owner encoded as r, s, v.
@return True, if transaction completes successfully
"""
assert owner != ZERO_ADDRESS # dev: invalid owner
assert expiry >= block.timestamp # dev: permit expired
nonce: uint256 = self.nonces[owner]
digest: bytes32 = keccak256(
concat(
b'\x19\x01',
self.domain_separator(),
keccak256(
concat(
PERMIT_TYPE_HASH,
convert(owner, bytes32),
convert(spender, bytes32),
convert(amount, bytes32),
convert(nonce, bytes32),
convert(expiry, bytes32),
)
)
)
)
# NOTE: signature is packed as r, s, v
r: uint256 = convert(slice(signature, 0, 32), uint256)
s: uint256 = convert(slice(signature, 32, 32), uint256)
v: uint256 = convert(slice(signature, 64, 1), uint256)
assert ecrecover(digest, v, r, s) == owner # dev: invalid signature
self.allowance[owner][spender] = amount
self.nonces[owner] = nonce + 1
log Approval(owner, spender, amount)
return True
@view
@internal
def _totalAssets() -> uint256:
# See note on `totalAssets()`.
return self.totalIdle + self.totalDebt
@view
@external
def totalAssets() -> uint256:
"""
@notice
Returns the total quantity of all assets under control of this
Vault, whether they're loaned out to a Strategy, or currently held in
the Vault.
@return The total assets under control of this Vault.
"""
return self._totalAssets()
@view
@internal
def _calculateLockedProfit() -> uint256:
lockedFundsRatio: uint256 = (block.timestamp - self.lastReport) * self.lockedProfitDegradation
if(lockedFundsRatio < DEGRADATION_COEFFICIENT):
lockedProfit: uint256 = self.lockedProfit
return lockedProfit - (
lockedFundsRatio
* lockedProfit
/ DEGRADATION_COEFFICIENT
)
else:
return 0
@view
@internal
def _freeFunds() -> uint256:
return self._totalAssets() - self._calculateLockedProfit()
@internal
def _issueSharesForAmount(to: address, amount: uint256) -> uint256:
# Issues `amount` Vault shares to `to`.
# Shares must be issued prior to taking on new collateral, or
# calculation will be wrong. This means that only *trusted* tokens
# (with no capability for exploitative behavior) can be used.
shares: uint256 = 0
# HACK: Saves 2 SLOADs (~200 gas, post-Berlin)
totalSupply: uint256 = self.totalSupply
if totalSupply > 0:
# Mint amount of shares based on what the Vault is managing overall
# NOTE: if sqrt(token.totalSupply()) > 1e39, this could potentially revert
shares = amount * totalSupply / self._freeFunds() # dev: no free funds
else:
# No existing shares, so mint 1:1
shares = amount
assert shares != 0 # dev: division rounding resulted in zero
# Mint new shares
self.totalSupply = totalSupply + shares
self.balanceOf[to] += shares
log Transfer(ZERO_ADDRESS, to, shares)
return shares
@external
@nonreentrant("withdraw")
def deposit(_amount: uint256 = MAX_UINT256, recipient: address = msg.sender) -> uint256:
"""
@notice
Deposits `_amount` `token`, issuing shares to `recipient`. If the
Vault is in Emergency Shutdown, deposits will not be accepted and this
call will fail.
@dev
Measuring quantity of shares to issues is based on the total
outstanding debt that this contract has ("expected value") instead
of the total balance sheet it has ("estimated value") has important
security considerations, and is done intentionally. If this value were
measured against external systems, it could be purposely manipulated by
an attacker to withdraw more assets than they otherwise should be able
to claim by redeeming their shares.
On deposit, this means that shares are issued against the total amount
that the deposited capital can be given in service of the debt that
Strategies assume. If that number were to be lower than the "expected
value" at some future point, depositing shares via this method could
entitle the depositor to *less* than the deposited value once the
"realized value" is updated from further reports by the Strategies
to the Vaults.
Care should be taken by integrators to account for this discrepancy,
by using the view-only methods of this contract (both off-chain and
on-chain) to determine if depositing into the Vault is a "good idea".
@param _amount The quantity of tokens to deposit, defaults to all.
@param recipient
The address to issue the shares in this Vault to. Defaults to the
caller's address.
@return The issued Vault shares.
"""
assert not self.emergencyShutdown # Deposits are locked out
assert recipient not in [self, ZERO_ADDRESS]
amount: uint256 = _amount
# If _amount not specified, transfer the full token balance,
# up to deposit limit
if amount == MAX_UINT256:
amount = min(
self.depositLimit - self._totalAssets(),
self.token.balanceOf(msg.sender),
)
else:
# Ensure deposit limit is respected
assert self._totalAssets() + amount <= self.depositLimit
# Ensure we are depositing something
assert amount > 0
# Issue new shares (needs to be done before taking deposit to be accurate)
# Shares are issued to recipient (may be different from msg.sender)
# See @dev note, above.
shares: uint256 = self._issueSharesForAmount(recipient, amount)
# Tokens are transferred from msg.sender (may be different from _recipient)
self.erc20_safe_transferFrom(self.token.address, msg.sender, self, amount)
self.totalIdle += amount
log Deposit(recipient, shares, amount)
return shares # Just in case someone wants them
@view
@internal
def _shareValue(shares: uint256) -> uint256:
# Returns price = 1:1 if vault is empty
if self.totalSupply == 0:
return shares
# Determines the current value of `shares`.
# NOTE: if sqrt(Vault.totalAssets()) >>> 1e39, this could potentially revert
return (
shares
* self._freeFunds()
/ self.totalSupply
)
@view
@internal
def _sharesForAmount(amount: uint256) -> uint256:
# Determines how many shares `amount` of token would receive.
# See dev note on `deposit`.
_freeFunds: uint256 = self._freeFunds()
if _freeFunds > 0:
# NOTE: if sqrt(token.totalSupply()) > 1e37, this could potentially revert
return (
amount
* self.totalSupply
/ _freeFunds
)
else:
return 0
@view
@external
def maxAvailableShares() -> uint256:
"""
@notice
Determines the maximum quantity of shares this Vault can facilitate a
withdrawal for, factoring in assets currently residing in the Vault,
as well as those deployed to strategies on the Vault's balance sheet.
@dev
Regarding how shares are calculated, see dev note on `deposit`.
If you want to calculated the maximum a user could withdraw up to,
you want to use this function.
Note that the amount provided by this function is the theoretical
maximum possible from withdrawing, the real amount depends on the
realized losses incurred during withdrawal.
@return The total quantity of shares this Vault can provide.
"""
shares: uint256 = self._sharesForAmount(self.totalIdle)
for strategy in self.withdrawalQueue:
if strategy == ZERO_ADDRESS:
break
shares += self._sharesForAmount(self.strategies[strategy].totalDebt)