-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathERC4626.vy
1195 lines (998 loc) · 45.1 KB
/
ERC4626.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.9
"""
@title Modern and Gas-Efficient ERC-4626 Tokenised Vault Implementation
@custom:contract-name ERC4626
@license GNU Affero General Public License v3.0
@author pcaversaccio
@notice These functions implement the ERC-4626
standard interface:
- https://eips.ethereum.org/EIPS/eip-4626.
In addition, the following functions have
been added for convenience:
- `permit` (`external` function),
- `nonces` (`external` `view` function),
- `DOMAIN_SEPARATOR` (`external` `view` function),
- `eip712Domain` (`external` `view` function).
The `permit` function implements approvals via
EIP-712 secp256k1 signatures:
https://eips.ethereum.org/EIPS/eip-2612.
In addition, this contract also implements the EIP-5267
function `eip712Domain`:
https://eips.ethereum.org/EIPS/eip-5267.
The implementation is inspired by OpenZeppelin's
implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol,
as well as by fubuloubu's implementation here:
https://github.com/fubuloubu/ERC4626/blob/main/contracts/VyperVault.vy.
@custom:security Most of the following security analysis was sourced from OpenZeppelin's
implementation: This implementation uses virtual assets and shares to
mitigate the risk of inflation attacks. The `internal` `immutable` variable
`_DECIMALS_OFFSET` corresponds to an offset in the decimal representation
between the underlying asset's decimals and the vault decimals. This offset
also determines the rate of virtual shares to virtual assets in the vault,
which itself determines the initial exchange rate. While not fully
preventing the attack, analysis (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/docs/modules/ROOT/pages/erc4626.adoc#security-concern-inflation-attack)
shows that a standard offset of `0` makes it non-profitable, as a result
of the value being captured by the virtual shares (out of the attacker's
donation) matching the attacker's expected gains. With a larger offset,
the attack becomes orders of magnitude more expensive than it is profitable.
More details about the underlying mathematics can be found here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/docs/modules/ROOT/pages/erc4626.adoc#security-concern-inflation-attack.
Furthermore, another potential approach would be that vault deployers can
protect against this attack by making an initial deposit of a non-trivial
amount of the asset, such that price manipulation becomes infeasible. For
the detailed discussion, please refer to:
https://ethereum-magicians.org/t/address-eip-4626-inflation-attacks-with-virtual-shares-and-assets/12677.
The drawback of the implemented approach is that the virtual shares do
capture (a very small) part of the value being accrued to the vault. Also,
if the vault experiences losses, the users try to exit the vault, the virtual
shares and assets will cause the first user to exit to experience reduced losses
in detriment to the last users that will experience bigger losses.
"""
# @dev We import and implement the `ERC20` interface,
# which is a built-in interface of the Vyper compiler.
from vyper.interfaces import ERC20
implements: ERC20
# @dev We import and implement the `ERC20Detailed` interface,
# which is a built-in interface of the Vyper compiler.
from vyper.interfaces import ERC20Detailed
implements: ERC20Detailed
# @dev We import and implement the `IERC20Permit`
# interface, which is written using standard Vyper
# syntax.
from ..tokens.interfaces.IERC20Permit import IERC20Permit
implements: IERC20Permit
# @dev We import and implement the `ERC4626` interface,
# which is a built-in interface of the Vyper compiler.
from vyper.interfaces import ERC4626
implements: ERC4626
# @dev We import and implement the `IERC5267` interface,
# which is written using standard Vyper syntax.
from ..utils.interfaces.IERC5267 import IERC5267
implements: IERC5267
# @dev Constant used as part of the ECDSA recovery function.
_MALLEABILITY_THRESHOLD: constant(bytes32) = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
# @dev The 32-byte type hash for the EIP-712 domain separator.
_TYPE_HASH: constant(bytes32) = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
# @dev The 32-byte type hash of the `permit` function.
_PERMIT_TYPE_HASH: constant(bytes32) = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
# @dev Returns the name of the token.
# @notice If you declare a variable as `public`,
# Vyper automatically generates an `external`
# getter function for the variable. Furthermore,
# to preserve consistency with the interface for
# the optional metadata functions of the ERC-20
# standard, we use lower case letters for the
# `immutable` variables `name`, `symbol`, and
# `decimals`.
name: public(immutable(String[25]))
# @dev Returns the symbol of the token.
# @notice See comment on lower case letters
# above at `name`.
symbol: public(immutable(String[5]))
# @dev Returns the decimals places of the token.
# @notice See comment on lower case letters
# above at `name`.
decimals: public(immutable(uint8))
# @dev Returns the address of the underlying token
# used for the vault for accounting, depositing,
# and withdrawing. To preserve consistency with the
# ERC-4626 interface, we use lower case letters for
# the `immutable` variable `name`.
# @notice Vyper returns the `address` type for interface
# types by default.
asset: public(immutable(ERC20))
# @dev Caches the domain separator as an `immutable`
# value, but also stores the corresponding chain ID
# to invalidate the cached domain separator if the
# chain ID changes.
_CACHED_DOMAIN_SEPARATOR: immutable(bytes32)
_CACHED_CHAIN_ID: immutable(uint256)
# @dev Caches `self` to `immutable` storage to avoid
# potential issues if a vanilla contract is used in
# a `delegatecall` context.
_CACHED_SELF: immutable(address)
# @dev `immutable` variables to store the (hashed)
# name and (hashed) version during contract creation.
_NAME: immutable(String[50])
_HASHED_NAME: immutable(bytes32)
_VERSION: immutable(String[20])
_HASHED_VERSION: immutable(bytes32)
# @dev An offset in the decimal representation between
# the underlying asset's decimals and the vault decimals.
# @notice While not fully preventing the attack, analysis
# (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/docs/modules/ROOT/pages/erc4626.adoc#security-concern-inflation-attack)
# shows that a standard offset of `0` makes an inflation
# attack non-profitable.
_DECIMALS_OFFSET: immutable(uint8)
# @dev Caches the underlying asset's decimals.
_UNDERLYING_DECIMALS: immutable(uint8)
# @dev Returns the amount of tokens owned by an `address`.
balanceOf: public(HashMap[address, uint256])
# @dev Returns the remaining number of tokens that a
# `spender` will be allowed to spend on behalf of
# `owner` through `transferFrom`. This is zero by
# default. This value changes when `approve`,
# `increase_allowance`, `decrease_allowance`, or
# `transferFrom` are called.
allowance: public(HashMap[address, HashMap[address, uint256]])
# @dev Returns the amount of tokens in existence.
totalSupply: public(uint256)
# @dev Returns the current on-chain tracked nonce
# of `address`.
nonces: public(HashMap[address, uint256])
# @dev Emitted when `amount` tokens are moved
# from one account (`owner`) to another (`to`).
# Note that the parameter `amount` may be zero.
event Transfer:
owner: indexed(address)
to: indexed(address)
amount: uint256
# @dev Emitted when the allowance of a `spender`
# for an `owner` is set by a call to `approve`.
# The parameter `amount` is the new allowance.
event Approval:
owner: indexed(address)
spender: indexed(address)
amount: uint256
# @dev Emitted when `sender` has exchanged `assets`
# for `shares`, and transferred those `shares`
# to `owner`.
event Deposit:
sender: indexed(address)
owner: indexed(address)
assets: uint256
shares: uint256
# @dev Emitted when `sender` has exchanged `shares`,
# owned by `owner`, for `assets`, and transferred
# those `assets` to `receiver`.
event Withdraw:
sender: indexed(address)
receiver: indexed(address)
owner: indexed(address)
assets: uint256
shares: uint256
# @dev May be emitted to signal that the domain could
# have changed.
event EIP712DomainChanged:
pass
@external
@payable
def __init__(name_: String[25], symbol_: String[5], asset_: ERC20, decimals_offset_: uint8, name_eip712_: String[50], version_eip712_: String[20]):
"""
@dev To omit the opcodes for checking the `msg.value`
in the creation-time EVM bytecode, the constructor
is declared as `payable`.
@param name_ The maximum 25-character user-readable
string name of the token.
@param symbol_ The maximum 5-character user-readable
string symbol of the token.
@param asset_ The ERC-20 compatible (i.e. ERC-777 is also viable)
underlying asset contract.
@param decimals_offset_ The 1-byte offset in the decimal
representation between the underlying asset's
decimals and the vault decimals. The recommended value to
mitigate the risk of an inflation attack is `0`.
@param name_eip712_ The maximum 50-character user-readable
string name of the signing domain, i.e. the name
of the dApp or protocol.
@param version_eip712_ The maximum 20-character current
main version of the signing domain. Signatures
from different versions are not compatible.
"""
name = name_
symbol = symbol_
asset = asset_
success: bool = empty(bool)
decoded_decimals: uint8 = empty(uint8)
# Attempt to fetch the underlying's decimals. A return
# value of `False` indicates that the attempt failed in
# some way.
success, decoded_decimals = self._try_get_underlying_decimals(asset_)
_UNDERLYING_DECIMALS = decoded_decimals if success else 18
_DECIMALS_OFFSET = decimals_offset_
# The following line uses intentionally checked arithmetic
# to prevent a theoretically possible overflow.
decimals = _UNDERLYING_DECIMALS + _DECIMALS_OFFSET
_NAME = name_eip712_
_VERSION = version_eip712_
_HASHED_NAME = keccak256(name_eip712_)
_HASHED_VERSION = keccak256(version_eip712_)
_CACHED_DOMAIN_SEPARATOR = self._build_domain_separator()
_CACHED_CHAIN_ID = chain.id
_CACHED_SELF = self
@external
def transfer(to: address, amount: uint256) -> bool:
"""
@dev Sourced from {ERC20-transfer}.
@notice See {ERC20-transfer} for the function
docstring.
"""
self._transfer(msg.sender, to, amount)
return True
@external
def approve(spender: address, amount: uint256) -> bool:
"""
@dev Sourced from {ERC20-approve}.
@notice See {ERC20-approve} for the function
docstring.
"""
self._approve(msg.sender, spender, amount)
return True
@external
def transferFrom(owner: address, to: address, amount: uint256) -> bool:
"""
@dev Sourced from {ERC20-transferFrom}.
@notice See {ERC20-transferFrom} for the function
docstring.
"""
self._spend_allowance(owner, msg.sender, amount)
self._transfer(owner, to, amount)
return True
@external
def increase_allowance(spender: address, added_amount: uint256) -> bool:
"""
@dev Sourced from {ERC20-increase_allowance}.
@notice See {ERC20-increase_allowance} for the
function docstring.
"""
self._approve(msg.sender, spender, self.allowance[msg.sender][spender] + added_amount)
return True
@external
def decrease_allowance(spender: address, subtracted_amount: uint256) -> bool:
"""
@dev Sourced from {ERC20-decrease_allowance}.
@notice See {ERC20-decrease_allowance} for the
function docstring.
"""
current_allowance: uint256 = self.allowance[msg.sender][spender]
assert current_allowance >= subtracted_amount, "ERC20: decreased allowance below zero"
self._approve(msg.sender, spender, unsafe_sub(current_allowance, subtracted_amount))
return True
@external
def permit(owner: address, spender: address, amount: uint256, deadline: uint256, v: uint8, r: bytes32, s: bytes32):
"""
@dev Sourced from {ERC20-permit}.
@notice See {ERC20-permit} for the function
docstring.
"""
assert block.timestamp <= deadline, "ERC20Permit: expired deadline"
current_nonce: uint256 = self.nonces[owner]
self.nonces[owner] = unsafe_add(current_nonce, 1)
struct_hash: bytes32 = keccak256(_abi_encode(_PERMIT_TYPE_HASH, owner, spender, amount, current_nonce, deadline))
hash: bytes32 = self._hash_typed_data_v4(struct_hash)
signer: address = self._recover_vrs(hash, convert(v, uint256), convert(r, uint256), convert(s, uint256))
assert signer == owner, "ERC20Permit: invalid signature"
self._approve(owner, spender, amount)
@external
@view
def DOMAIN_SEPARATOR() -> bytes32:
"""
@dev Sourced from {ERC20-DOMAIN_SEPARATOR}.
@notice See {ERC20-DOMAIN_SEPARATOR} for the
function docstring.
"""
return self._domain_separator_v4()
@external
@view
def eip712Domain() -> (bytes1, String[50], String[20], uint256, address, bytes32, DynArray[uint256, 128]):
"""
@dev Returns the fields and values that describe the domain
separator used by this contract for EIP-712 signatures.
@notice The bits in the 1-byte bit map are read from the least
significant to the most significant, and fields are indexed
in the order that is specified by EIP-712, identical to the
order in which they are listed in the function type.
@return bytes1 The 1-byte bit map where bit `i` is set to 1
if and only if domain field `i` is present (`0 ≤ i ≤ 4`).
@return String The maximum 50-character user-readable string name
of the signing domain, i.e. the name of the dApp or protocol.
@return String The maximum 20-character current main version of
the signing domain. Signatures from different versions are
not compatible.
@return uint256 The 32-byte EIP-155 chain ID.
@return address The 20-byte address of the verifying contract.
@return bytes32 The 32-byte disambiguation salt for the protocol.
@return DynArray The 32-byte array of EIP-712 extensions.
"""
# Note that `\x0f` equals `01111`.
return (convert(b"\x0f", bytes1), _NAME, _VERSION, chain.id, self, empty(bytes32), empty(DynArray[uint256, 128]))
@external
@view
def totalAssets() -> uint256:
"""
@dev Returns the total amount of the underlying asset
that is managed by the vault.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#totalassets.
@return uint256 The 32-byte total managed assets.
"""
return self._total_assets()
@external
@view
def convertToShares(assets: uint256) -> uint256:
"""
@dev Returns the amount of shares that the vault would
exchange for the amount of assets provided, in an
ideal scenario where all the conditions are met.
@notice Note that the conversion must round down to 0.
For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#converttoshares.
@param assets The 32-byte assets amount.
@return uint256 The converted 32-byte shares amount.
"""
return self._convert_to_shares(assets, False)
@external
@view
def convertToAssets(shares: uint256) -> uint256:
"""
@dev Returns the amount of assets that the vault would
exchange for the amount of shares provided, in an
ideal scenario where all the conditions are met.
@notice Note that the conversion must round down to 0.
For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#converttoassets.
@param shares The 32-byte shares amount.
@return uint256 The converted 32-byte assets amount.
"""
return self._convert_to_assets(shares, False)
@external
@view
def maxDeposit(receiver: address) -> uint256:
"""
@dev Returns the maximum amount of the underlying asset
that can be deposited into the vault for the `receiver`,
through a `deposit` call.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#maxdeposit.
@param receiver The 20-byte receiver address.
@return uint256 The 32-byte maximum deposit amount.
"""
return self._max_deposit(receiver)
@external
@view
def previewDeposit(assets: uint256) -> uint256:
"""
@dev Allows an on-chain or off-chain user to simulate the
effects of their deposit at the current block, given
current on-chain conditions.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#previewdeposit.
@param assets The 32-byte assets amount.
@return uint256 The simulated 32-byte returning shares amount.
"""
return self._preview_deposit(assets)
@external
def deposit(assets: uint256, receiver: address) -> uint256:
"""
@dev Mints `shares` vault shares to `receiver` by depositing
exactly `assets` of underlying tokens.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#deposit.
@param assets The 32-byte assets amount.
@param receiver The 20-byte receiver address.
@return uint256 The 32-byte shares amount to be created.
"""
assert assets <= self._max_deposit(receiver), "ERC4626: deposit more than maximum"
shares: uint256 = self._preview_deposit(assets)
self._deposit(msg.sender, receiver, assets, shares)
return shares
@external
@view
def maxMint(receiver: address) -> uint256:
"""
@dev Returns the maximum amount of shares that can be minted
from the vault for the `receiver`, through a `mint` call.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#maxmint.
@param receiver The 20-byte receiver address.
@return uint256 The 32-byte maximum mint amount.
"""
return self._max_mint(receiver)
@external
@view
def previewMint(shares: uint256) -> uint256:
"""
@dev Allows an on-chain or off-chain user to simulate the
effects of their `mint` at the current block, given
current on-chain conditions.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#previewmint.
@param shares The 32-byte shares amount.
@return uint256 The simulated 32-byte required assets amount.
"""
return self._preview_mint(shares)
@external
def mint(shares: uint256, receiver:address) -> uint256:
"""
@dev Mints exactly `shares` vault shares to `receiver` by
depositing `assets` of underlying tokens.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#mint.
@param shares The 32-byte shares amount to be created.
@param receiver The 20-byte receiver address.
@return uint256 The deposited 32-byte assets amount.
"""
assert shares <= self._max_mint(receiver), "ERC4626: mint more than maximum"
assets: uint256 = self._preview_mint(shares)
self._deposit(msg.sender, receiver, assets, shares)
return assets
@external
@view
def maxWithdraw(owner: address) -> uint256:
"""
@dev Returns the maximum amount of the underlying asset that
can be withdrawn from the owner balance in the vault,
through a `withdraw` call.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#maxwithdraw.
@param owner The 20-byte owner address.
@return uint256 The 32-byte maximum withdraw amount.
"""
return self._max_withdraw(owner)
@external
@view
def previewWithdraw(assets: uint256) -> uint256:
"""
@dev Allows an on-chain or off-chain user to simulate the
effects of their withdrawal at the current block, given
current on-chain conditions.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#previewwithdraw.
@param assets The 32-byte assets amount.
@return uint256 The simulated 32-byte burned shares amount.
"""
return self._preview_withdraw(assets)
@external
def withdraw(assets: uint256, receiver: address, owner: address) -> uint256:
"""
@dev Burns `shares` from `owner` and sends exactly `assets` of
underlying tokens to `receiver`.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#withdraw.
@param assets The 32-byte assets amount to be withdrawn.
@param receiver The 20-byte receiver address.
@param owner The 20-byte owner address.
@return uint256 The burned 32-byte shares amount.
"""
assert assets <= self._max_withdraw(receiver), "ERC4626: withdraw more than maximum"
shares: uint256 = self._preview_withdraw(assets)
self._withdraw(msg.sender, receiver, owner, assets, shares)
return shares
@external
@view
def maxRedeem(owner: address) -> uint256:
"""
@dev Maximum amount of vault shares that can be redeemed from
the `owner` balance in the vault, through a `redeem` call.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#maxredeem.
@param owner The 20-byte owner address.
@return uint256 The 32-byte maximum redeemable shares amount.
"""
return self._max_redeem(owner)
@external
@view
def previewRedeem(shares: uint256) -> uint256:
"""
@dev Allows an on-chain or off-chain user to simulate the effects
of their redeemption at the current block, given current
on-chain conditions.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#previewredeem.
@param shares The 32-byte shares amount to be redeemed.
@return uint256 The simulated 32-byte returning assets amount.
"""
return self._preview_redeem(shares)
@external
def redeem(shares: uint256, receiver: address, owner: address) -> uint256:
"""
@dev Burns exactly `shares` from `owner` and sends `assets` of
underlying tokens to `receiver`.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#redeem.
@param shares The 32-byte redeemed shares amount.
@param receiver The 20-byte receiver address.
@param owner The 20-byte owner address.
@return uint256 The returned 32-byte assets amount.
"""
assert shares <= self._max_redeem(owner), "ERC4626: redeem more than maximum"
assets: uint256 = self._preview_redeem(shares)
self._withdraw(msg.sender, receiver, owner, assets, shares)
return assets
@internal
def _transfer(owner: address, to: address, amount: uint256):
"""
@dev Sourced from {ERC20-_transfer}.
@notice See {ERC20-_transfer} for the function
docstring.
"""
assert owner != empty(address), "ERC20: transfer from the zero address"
assert to != empty(address), "ERC20: transfer to the zero address"
self._before_token_transfer(owner, to, amount)
owner_balanceOf: uint256 = self.balanceOf[owner]
assert owner_balanceOf >= amount, "ERC20: transfer amount exceeds balance"
self.balanceOf[owner] = unsafe_sub(owner_balanceOf, amount)
self.balanceOf[to] = unsafe_add(self.balanceOf[to], amount)
log Transfer(owner, to, amount)
self._after_token_transfer(owner, to, amount)
@internal
def _mint(owner: address, amount: uint256):
"""
@dev Sourced from {ERC20-_mint}.
@notice See {ERC20-_mint} for the function
docstring.
"""
assert owner != empty(address), "ERC20: mint to the zero address"
self._before_token_transfer(empty(address), owner, amount)
self.totalSupply += amount
self.balanceOf[owner] = unsafe_add(self.balanceOf[owner], amount)
log Transfer(empty(address), owner, amount)
self._after_token_transfer(empty(address), owner, amount)
@internal
def _burn(owner: address, amount: uint256):
"""
@dev Sourced from {ERC20-_burn}.
@notice See {ERC20-_burn} for the function
docstring.
"""
assert owner != empty(address), "ERC20: burn from the zero address"
self._before_token_transfer(owner, empty(address), amount)
account_balance: uint256 = self.balanceOf[owner]
assert account_balance >= amount, "ERC20: burn amount exceeds balance"
self.balanceOf[owner] = unsafe_sub(account_balance, amount)
self.totalSupply = unsafe_sub(self.totalSupply, amount)
log Transfer(owner, empty(address), amount)
self._after_token_transfer(owner, empty(address), amount)
@internal
def _approve(owner: address, spender: address, amount: uint256):
"""
@dev Sourced from {ERC20-_approve}.
@notice See {ERC20-_approve} for the function
docstring.
"""
assert owner != empty(address), "ERC20: approve from the zero address"
assert spender != empty(address), "ERC20: approve to the zero address"
self.allowance[owner][spender] = amount
log Approval(owner, spender, amount)
@internal
def _spend_allowance(owner: address, spender: address, amount: uint256):
"""
@dev Sourced from {ERC20-_approve}.
@notice See {ERC20-_spend_allowance} for the
function docstring.
"""
current_allowance: uint256 = self.allowance[owner][spender]
if (current_allowance != max_value(uint256)):
# The following line allows the commonly known address
# poisoning attack, where `transferFrom` instructions
# are executed from arbitrary addresses with an `amount`
# of 0. However, this poisoning attack is not an on-chain
# vulnerability. All assets are safe. It is an off-chain
# log interpretation issue.
assert current_allowance >= amount, "ERC20: insufficient allowance"
self._approve(owner, spender, unsafe_sub(current_allowance, amount))
@internal
def _before_token_transfer(owner: address, to: address, amount: uint256):
"""
@dev Sourced from {ERC20-_before_token_transfer}.
@notice See {ERC20-_before_token_transfer} for
the function docstring.
"""
pass
@internal
def _after_token_transfer(owner: address, to: address, amount: uint256):
"""
@dev Sourced from {ERC20-_after_token_transfer}.
@notice See {ERC20-_after_token_transfer} for
the function docstring.
"""
pass
@internal
@view
def _domain_separator_v4() -> bytes32:
"""
@dev Sourced from {EIP712DomainSeparator-domain_separator_v4}.
@notice See {EIP712DomainSeparator-domain_separator_v4}
for the function docstring.
"""
if (self == _CACHED_SELF and chain.id == _CACHED_CHAIN_ID):
return _CACHED_DOMAIN_SEPARATOR
else:
return self._build_domain_separator()
@internal
@view
def _build_domain_separator() -> bytes32:
"""
@dev Sourced from {EIP712DomainSeparator-_build_domain_separator}.
@notice See {EIP712DomainSeparator-_build_domain_separator}
for the function docstring.
"""
return keccak256(_abi_encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, chain.id, self))
@internal
@view
def _hash_typed_data_v4(struct_hash: bytes32) -> bytes32:
"""
@dev Sourced from {EIP712DomainSeparator-hash_typed_data_v4}.
@notice See {EIP712DomainSeparator-hash_typed_data_v4}
for the function docstring.
"""
return self._to_typed_data_hash(self._domain_separator_v4(), struct_hash)
@internal
@pure
def _to_typed_data_hash(domain_separator: bytes32, struct_hash: bytes32) -> bytes32:
"""
@dev Sourced from {ECDSA-to_typed_data_hash}.
@notice See {ECDSA-to_typed_data_hash} for the
function docstring.
"""
return keccak256(concat(b"\x19\x01", domain_separator, struct_hash))
@internal
@pure
def _recover_vrs(hash: bytes32, v: uint256, r: uint256, s: uint256) -> address:
"""
@dev Sourced from {ECDSA-_recover_vrs}.
@notice See {ECDSA-_recover_vrs} for the
function docstring.
"""
return self._try_recover_vrs(hash, v, r, s)
@internal
@pure
def _try_recover_vrs(hash: bytes32, v: uint256, r: uint256, s: uint256) -> address:
"""
@dev Sourced from {ECDSA-_try_recover_vrs}.
@notice See {ECDSA-_try_recover_vrs} for the
function docstring.
"""
if (s > convert(_MALLEABILITY_THRESHOLD, uint256)):
raise "ECDSA: invalid signature 's' value"
signer: address = ecrecover(hash, v, r, s)
if (signer == empty(address)):
raise "ECDSA: invalid signature"
return signer
@internal
@view
def _try_get_underlying_decimals(underlying: ERC20) -> (bool, uint8):
"""
@dev Attempts to fetch the underlying's decimals. A return
value of `False` indicates that the attempt failed in
some way.
@param underlying The ERC-20 compatible (i.e. ERC-777 is also viable)
underlying asset contract.
@return bool The verification whether the call succeeded or
failed.
@return uint8 The fetched underlying's decimals.
"""
success: bool = empty(bool)
return_data: Bytes[32] = b""
# The following low-level call does not revert, but instead
# returns `False` if the callable contract does not implement
# the `decimals` function. Since we perform a length check of
# 32 bytes for the return data in the return expression at the
# end, we also return `False` for EOA wallets instead of reverting
# (remember that the EVM always considers a call to an EOA as
# successful with return data `0x`). Furthermore, it is important
# to note that an external call via `raw_call` does not perform an
# external code size check on the target address.
success, return_data = raw_call(underlying.address, method_id("decimals()"), max_outsize=32, is_static_call=True, revert_on_failure=False)
if (success and (len(return_data) == 32) and (convert(return_data, uint256) <= convert(max_value(uint8), uint256))):
return (True, convert(return_data, uint8))
return (False, empty(uint8))
@internal
@view
def _total_assets() -> uint256:
"""
@dev An `internal` helper function that returns the total amount
of the underlying asset that is managed by the vault.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#totalassets.
@return uint256 The 32-byte total managed assets.
"""
return asset.balanceOf(self)
@internal
@view
def _convert_to_shares(assets: uint256, roundup: bool) -> uint256:
"""
@dev An `internal` conversion function (from assets to shares)
with support for rounding direction.
@param assets The 32-byte assets amount.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The converted 32-byte shares amount.
"""
return self._mul_div(assets, self.totalSupply + 10 ** convert(_DECIMALS_OFFSET, uint256), self._total_assets() + 1, roundup)
@internal
@view
def _convert_to_assets(shares: uint256, roundup: bool) -> uint256:
"""
@dev An `internal` conversion function (from shares to assets)
with support for rounding direction.
@param shares The 32-byte shares amount.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The converted 32-byte assets amount.
"""
return self._mul_div(shares, self._total_assets() + 1, self.totalSupply + 10 ** convert(_DECIMALS_OFFSET, uint256), roundup)
@internal
@pure
def _max_deposit(receiver: address) -> uint256:
"""
@dev An `internal` helper function that returns the maximum
amount of the underlying asset that can be deposited into
the vault for the `receiver`, through a `deposit` call.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#maxdeposit.
@param receiver The 20-byte receiver address.
@return uint256 The 32-byte maximum deposit amount.
"""
return max_value(uint256)
@internal
@view
def _preview_deposit(assets: uint256) -> uint256:
"""
@dev An `internal` helper function that allows an on-chain or
off-chain user to simulate the effects of their deposit at
the current block, given current on-chain conditions.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#previewdeposit.
@param assets The 32-byte assets amount.
@return uint256 The simulated 32-byte returning shares amount.
"""
return self._convert_to_shares(assets, False)
@internal
@pure
def _max_mint(receiver: address) -> uint256:
"""
@dev An `internal` helper function that returns the maximum
amount of shares that can be minted from the vault for
the `receiver`, through a `mint` call.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#maxmint.
@param receiver The 20-byte receiver address.
@return uint256 The 32-byte maximum mint amount.
"""
return max_value(uint256)
@internal
@view
def _preview_mint(shares: uint256) -> uint256:
"""
@dev An `internal` helper function that allows an on-chain or
off-chain user to simulate the effects of their `mint` at
the current block, given current on-chain conditions.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#previewmint.
@param shares The 32-byte shares amount.
@return uint256 The simulated 32-byte required assets amount.
"""
return self._convert_to_assets(shares, True)
@internal
@view
def _max_withdraw(owner: address) -> uint256:
"""
@dev An `internal` helper function that returns the maximum
amount of the underlying asset that can be withdrawn from
the owner balance in the vault, through a `withdraw` call.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#maxwithdraw.
@param owner The 20-byte owner address.
@return uint256 The 32-byte maximum withdraw amount.
"""
return self._convert_to_assets(self.balanceOf[owner], False)
@internal
@view
def _preview_withdraw(assets: uint256) -> uint256:
"""
@dev An `internal` helper function that allows an on-chain or
off-chain user to simulate the effects of their withdrawal
at the current block, given current on-chain conditions.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#previewwithdraw.
@param assets The 32-byte assets amount.
@return uint256 The simulated 32-byte burned shares amount.
"""
return self._convert_to_shares(assets, True)
@internal
@view
def _max_redeem(owner: address) -> uint256:
"""
@dev An `internal` helper function that returns the maximum
amount of vault shares that can be redeemed from the `owner`
balance in the vault, through a `redeem` call.
@notice For the to be fulfilled conditions, please refer to:
https://eips.ethereum.org/EIPS/eip-4626#maxredeem.
@param owner The 20-byte owner address.
@return uint256 The 32-byte maximum redeemable shares amount.
"""
return self.balanceOf[owner]
@internal
@view
def _preview_redeem(shares: uint256) -> uint256: