-
Notifications
You must be signed in to change notification settings - Fork 320
/
Vault.vy
1551 lines (1273 loc) · 56.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.2.8
"""
@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/master/SPECIFICATION.md
"""
API_VERSION: constant(String[28]) = "0.2.2"
# TODO: Add ETH Configuration
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 estimatedTotalAssets() -> uint256: view
def withdraw(_amount: uint256): nonpayable
def migrate(_newStrategy: address): nonpayable
interface GuestList:
def authorized(guest: address, amount: uint256) -> bool: view
event Transfer:
sender: indexed(address)
receiver: indexed(address)
value: uint256
event Approval:
owner: indexed(address)
spender: indexed(address)
value: uint256
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)
guardian: public(address)
pendingGovernance: address
guestList: public(GuestList)
struct StrategyParams:
performanceFee: uint256 # Strategist's fee (basis points)
activation: uint256 # Activation block.number
debtLimit: uint256 # Maximum borrow amount
rateLimit: uint256 # Max increase in debt per second 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 StrategyAdded:
strategy: indexed(address)
debtLimit: uint256 # Maximum borrow amount
rateLimit: uint256 # Increase/decrease per block
performanceFee: uint256 # Strategist's fee (basis points)
event StrategyReported:
strategy: indexed(address)
gain: uint256
loss: uint256
totalGain: uint256
totalLoss: uint256
totalDebt: uint256
debtAdded: uint256
debtLimit: uint256
event UpdateGovernance:
governance: address # New active governance
event UpdateGuestList:
guestList: address # Vault guest list address
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 StrategyUpdateDebtLimit:
strategy: indexed(address) # Address of the strategy for the debt limit adjustment
debtLimit: uint256 # The new debt limit for the strategy
event StrategyUpdateRateLimit:
strategy: indexed(address) # Address of the strategy for the rate limit adjustment
rateLimit: uint256 # The new rate limit for the strategy
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
# NOTE: Track the total for overhead targeting purposes
strategies: public(HashMap[address, StrategyParams])
MAXIMUM_STRATEGIES: constant(uint256) = 20
# 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
debtLimit: public(uint256) # Debt limit for the Vault across all strategies
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
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)
FEE_MAX: constant(uint256) = 10_000 # 100%, or 10k basis points
SECS_PER_YEAR: constant(uint256) = 31_557_600 # 365.25 days
# `nonces` track `permit` approvals with signature.
nonces: public(HashMap[address, uint256])
DOMAIN_SEPARATOR: public(bytes32)
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 __init__(
token: address,
governance: address,
rewards: address,
nameOverride: String[64],
symbolOverride: String[32],
):
"""
@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.
There is no initial deposit limit.
@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 'y'
combined with the symbol of `token`.
@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 nameOverride Specify a custom Vault name. Leave empty for default choice.
@param symbolOverride Specify a custom Vault symbol name. Leave empty for default choice.
"""
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
self.decimals = DetailedERC20(token).decimals()
self.governance = governance
log UpdateGovernance(governance)
self.rewards = rewards
log UpdateRewards(rewards)
self.guardian = msg.sender
log UpdateGuardian(msg.sender)
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.depositLimit = MAX_UINT256 # Start unlimited
log UpdateDepositLimit(MAX_UINT256)
self.lastReport = block.timestamp
self.activation = block.timestamp
# EIP-712
self.DOMAIN_SEPARATOR = keccak256(
concat(
DOMAIN_TYPE_HASH,
keccak256(convert("Yearn Vault", Bytes[11])),
keccak256(convert(API_VERSION, Bytes[28])),
convert(chain.id, bytes32),
convert(self, bytes32)
)
)
@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
@external
def setName(name: String[42]):
"""
@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[20]):
"""
@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
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 setGuestList(guestList: address):
"""
@notice
Used to set or change `guestList`. A guest list is another contract
that dictates who is allowed to participate in a Vault (and transfer
shares).
This may only be called by governance.
@param guestList The address of the `GuestList` contract to use.
"""
assert msg.sender == self.governance
self.guestList = GuestList(guestList)
log UpdateGuestList(guestList)
@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
self.rewards = rewards
log UpdateRewards(rewards)
@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`.
This may only be called by governance.
@param fee The new performance fee to use.
"""
assert msg.sender == self.governance
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
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.
"""
assert msg.sender in [self.guardian, 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.
@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 == self.governance
# HACK: Temporary until Vyper adds support for Dynamic arrays
for i in range(MAXIMUM_STRATEGIES):
if queue[i] == ZERO_ADDRESS and self.withdrawalQueue[i] == ZERO_ADDRESS:
break
assert self.strategies[queue[i]].activation > 0
self.withdrawalQueue[i] = queue[i]
log UpdateWithdrawalQueue(queue)
@internal
def _transfer(sender: address, receiver: address, amount: uint256):
# See note on `transfer()`.
# Protect people from accidentally sending their shares to bad places
assert not (receiver 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 == 0 or 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 receivertalAssets() -> uint256:
# See note on `totalAssets()`.
return self.token.balanceOf(self) + 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.receivertalAssets()
@view
@internal
def _balanceSheetOfStrategy(strategy: address) -> uint256:
# See note on `balanceSheetOfStrategy()`.
return Strategy(strategy).estimatedTotalAssets()
@view
@external
def balanceSheetOfStrategy(strategy: address) -> uint256:
"""
@notice
Provide an accurate estimate for the total amount of assets
(principle + return) that `strategy` is currently managing,
denominated in terms of `token`.
This total is the total realizable value that could *actually* be
obtained from this Strategy if it were to divest its entire position
based on current on-chain conditions.
@param strategy The Strategy to estimate the realizable assets of.
@return An estimate of the total realizable assets in `strategy`.
"""
return self._balanceSheetOfStrategy(strategy)
@view
@external
def totalBalanceSheet(strategies: address[2 * MAXIMUM_STRATEGIES]) -> uint256:
"""
@notice
Measure the total balance sheet of this Vault, using the list of
strategies given above.
(2x the expected maximum is used to ensure completeness.)
NOTE: The safety of this function depends *entirely* on the list of
strategies given as the function argument. Care should be taken to
choose this list to ensure that the estimate is accurate. No
additional checking is used.
NOTE: Guardian should use this value vs. `totalAssets()` to determine
if a condition exists where the Vault is experiencing a dangerous
'balance sheet' attack, leading Vault shares to be worth less than
what their price on paper is (based on their debt)
@param strategies
A list of strategies managed by this Vault, which will be included in
the balance sheet calculation.
@return The total balance sheet of this Vault.
"""
balanceSheet: uint256 = self.token.balanceOf(self)
for strategy in strategies:
if strategy == ZERO_ADDRESS:
break
balanceSheet += self._balanceSheetOfStrategy(strategy)
return balanceSheet
@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 (~4000 gas)
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.receivertalAssets()
else:
# No existing shares, so mint 1:1
shares = amount
# Mint new shares
self.totalSupply = totalSupply + shares
self.balanceOf[to] += shares
log Transfer(ZERO_ADDRESS, to, shares)
return shares
@external
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
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.receivertalAssets(),
self.token.balanceOf(msg.sender),
)
else:
# Ensure deposit limit is respected
assert self.receivertalAssets() + amount <= self.depositLimit
# Ensure we are depositing something
assert amount > 0
# Ensure deposit is permitted by guest list
if self.guestList.address != ZERO_ADDRESS:
assert self.guestList.authorized(msg.sender, amount)
# 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)
assert self.token.transferFrom(msg.sender, self, amount)
return shares # Just in case someone wants them
@view
@internal
def _shareValue(shares: uint256) -> uint256:
# Determines the current value of `shares`.
# NOTE: if sqrt(Vault.totalAssets()) >>> 1e39, this could potentially revert
return (shares * (self.receivertalAssets())) / self.totalSupply
@view
@internal
def _sharesForAmount(amount: uint256) -> uint256:
# Determines how many shares `amount` of token would receive.
# See dev note on `deposit`.
if self.receivertalAssets() > 0:
# NOTE: if sqrt(token.totalSupply()) > 1e39, this could potentially revert
return (amount * self.totalSupply) / self.receivertalAssets()
else:
return 0
@view
@external
def maxAvailableShares() -> uint256:
"""
@notice
Determines the total quantity of shares this Vault can provide,
factoring in assets currently residing in the Vault, as well as
those deployed to strategies.
@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.
@return The total quantity of shares this Vault can provide.
"""
shares: uint256 = self._sharesForAmount(self.token.balanceOf(self))
for strategy in self.withdrawalQueue:
if strategy == ZERO_ADDRESS:
break
shares += self._sharesForAmount(self.strategies[strategy].totalDebt)
return shares
@external
def withdraw(_shares: uint256 = MAX_UINT256, recipient: address = msg.sender) -> uint256:
"""
@notice
Withdraws the calling account's tokens from this Vault, redeeming
amount `_shares` for an appropriate amount of tokens.
See note on `setWithdrawalQueue` for further details of withdrawal
ordering and behavior.
@dev
Measuring the value of shares 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 withdrawal, this means that shares are redeemed against the total
amount that the deposited capital had "realized" since the point it
was deposited, up until the point it was withdrawn. If that number
were to be higher than the "expected value" at some future point,
withdrawing shares via this method could entitle the depositor to
*more* than the expected value once the "realized value" is updated
from further reports by the Strategies to the Vaults.
Under exceptional scenarios, this could cause earlier withdrawals to
earn "more" of the underlying assets than Users might otherwise be
entitled to, if the Vault's estimated value were otherwise measured
through external means, accounting for whatever exceptional scenarios
exist for the Vault (that aren't covered by the Vault's own design.)
@param _shares How many shares to redeem for tokens, defaults to all.
@param recipient
The address to issue the shares in this Vault to. Defaults to the
caller's address.
@return The quantity of tokens redeemable for `_shares`.
"""
shares: uint256 = _shares # May reduce this number below
# If _shares not specified, transfer full share balance
if shares == MAX_UINT256:
shares = self.balanceOf[msg.sender]
# Limit to only the shares they own
assert shares <= self.balanceOf[msg.sender]
# See @dev note, above.
value: uint256 = self._shareValue(shares)
if value > self.token.balanceOf(self):
# We need to go get some from our strategies in the withdrawal queue
# NOTE: This performs forced withdrawals from each Strategy. There is
# a 0.5% withdrawal fee assessed on each forced withdrawal (<= 0.5% total)
for strategy in self.withdrawalQueue:
if strategy == ZERO_ADDRESS:
break # We've exhausted the queue
if value <= self.token.balanceOf(self):
break # We're done withdrawing
amountNeeded: uint256 = value - self.token.balanceOf(self)
# NOTE: Don't withdraw more than the debt so that Strategy can still
# continue to work based on the profits it has
# NOTE: This means that user will lose out on any profits that each
# Strategy in the queue would return on next harvest, benefiting others
amountNeeded = min(amountNeeded, self.strategies[strategy].totalDebt)
if amountNeeded == 0:
continue # Nothing to withdraw from this Strategy, try the next one
# Force withdraw amount from each Strategy in the order set by governance
before: uint256 = self.token.balanceOf(self)
Strategy(strategy).withdraw(amountNeeded)
withdrawn: uint256 = self.token.balanceOf(self) - before
# Reduce the Strategy's debt by the amount withdrawn ("realized returns")
# NOTE: This doesn't add to returns as it's not earned by "normal means"
self.strategies[strategy].totalDebt -= withdrawn
self.totalDebt -= withdrawn
# NOTE: We have withdrawn everything possible out of the withdrawal queue
# but we still don't have enough to fully pay them back, so adjust
# to the total amount we've freed up through forced withdrawals
if value > self.token.balanceOf(self):
value = self.token.balanceOf(self)
shares = self._sharesForAmount(value)
# Burn shares (full value of what is being withdrawn)
self.totalSupply -= shares
self.balanceOf[msg.sender] -= shares
log Transfer(msg.sender, ZERO_ADDRESS, shares)
# Withdraw remaining balance to _recipient (may be different to msg.sender) (minus fee)
assert self.token.transfer(recipient, value)
return value
@view
@external
def pricePerShare() -> uint256:
"""
@notice Gives the price for a single Vault share.
@dev See dev note on `withdraw`.
@return The value of a single share.
"""
if self.totalSupply == 0:
return 10 ** self.decimals # price of 1:1
else:
return self._shareValue(10 ** self.decimals)
@internal
def _organizeWithdrawalQueue():
# Reorganize `withdrawalQueue` based on premise that if there is an
# empty value between two actual values, then the empty value should be
# replaced by the later value.
# NOTE: Relative ordering of non-zero values is maintained.
offset: uint256 = 0
for idx in range(MAXIMUM_STRATEGIES):
strategy: address = self.withdrawalQueue[idx]