forked from 0xIntuition/intuition-contracts-v0.1
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEthMultiVault.sol
1447 lines (1196 loc) · 59.6 KB
/
EthMultiVault.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.21;
import {BeaconProxy} from "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {IEntryPoint} from "account-abstraction/contracts/interfaces/IEntryPoint.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {LibZip} from "solady/utils/LibZip.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {SafeCastLib} from "solmate/utils/SafeCastLib.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {AtomWallet} from "src/AtomWallet.sol";
import {Errors} from "src/libraries/Errors.sol";
import {IEthMultiVault} from "src/interfaces/IEthMultiVault.sol";
import {IPermit2} from "src/interfaces/IPermit2.sol";
/**
* @title EthMultiVault
* @author 0xIntuition
* @notice Core contract of the Intuition protocol. Manages the creation and management of vaults
* associated with atoms & triples.
*/
contract EthMultiVault is IEthMultiVault, Initializable, ReentrancyGuardUpgradeable, PausableUpgradeable {
using FixedPointMathLib for uint256;
using LibZip for bytes;
/* =================================================== */
/* STATE VARIABLES */
/* =================================================== */
// Operation identifiers
bytes32 public constant SET_ADMIN = keccak256("setAdmin");
bytes32 public constant SET_EXIT_FEE = keccak256("setExitFee");
/// @notice Configuration structs
GeneralConfig public generalConfig;
AtomConfig public atomConfig;
TripleConfig public tripleConfig;
WalletConfig public walletConfig;
/// @notice ID of the last vault to be created
uint256 public count;
/// @notice Mapping of vault ID to vault state
// Vault ID -> Vault State
mapping(uint256 vaultId => VaultState vaultState) public vaults;
/// @notice Mapping of vault ID to vault fees
// Vault ID -> Vault Fees
mapping(uint256 vaultId => VaultFees vaultFees) public vaultFees;
/// @notice RDF (Resource Description Framework)
// mapping of vault ID to atom data
// Vault ID -> Atom Data
mapping(uint256 atomId => bytes atomData) public atoms;
// mapping of atom hash to atom vault ID
// Hash -> Atom ID
mapping(bytes32 atomHash => uint256 atomId) public atomsByHash;
// mapping of triple vault ID to the underlying atom IDs that make up the triple
// Triple ID -> VaultIDs of atoms that make up the triple
mapping(uint256 tripleId => uint256[3] tripleAtomIds) public triples;
// mapping of triple hash to triple vault ID
// Hash -> Triple ID
mapping(bytes32 tripleHash => uint256 tripleId) public triplesByHash;
// mapping of triple vault IDs to determine whether a vault is a triple or not
// Vault ID -> (Is Triple)
mapping(uint256 vaultId => bool isTriple) public isTriple;
/// @notice Atom Shares Tracking
/// used to enable atom shares earned from triple deposits to be redeemed proportionally
/// to the triple shares that earned them upon redemption/withdraw
/// Triple ID -> Atom ID -> Account Address -> Atom Share Balance
mapping(uint256 tripleId => mapping(uint256 atomId => mapping(address account => uint256 balance))) public
tripleAtomShares;
/// @notice Timelock mapping (operation hash -> timelock struct)
mapping(bytes32 operationHash => Timelock timelock) public timelocks;
/* =================================================== */
/* MODIFIERS */
/* =================================================== */
modifier onlyAdmin() {
if (msg.sender != generalConfig.admin) {
revert Errors.MultiVault_AdminOnly();
}
_;
}
/* =================================================== */
/* INITIALIZER */
/* =================================================== */
/// @notice Initializes the MultiVault contract
///
/// @param _generalConfig General configuration struct
/// @param _atomConfig Atom configuration struct
/// @param _tripleConfig Triple configuration struct
/// @param _walletConfig Wallet configuration struct
/// @param _defaultVaultFees Default vault fees struct
///
/// NOTE: This function is called only once (during contract deployment)
function init(
GeneralConfig memory _generalConfig,
AtomConfig memory _atomConfig,
TripleConfig memory _tripleConfig,
WalletConfig memory _walletConfig,
VaultFees memory _defaultVaultFees
) external initializer {
__ReentrancyGuard_init();
__Pausable_init();
generalConfig = _generalConfig;
atomConfig = _atomConfig;
tripleConfig = _tripleConfig;
walletConfig = _walletConfig;
vaultFees[0] = VaultFees({
entryFee: _defaultVaultFees.entryFee,
exitFee: _defaultVaultFees.exitFee,
protocolFee: _defaultVaultFees.protocolFee
});
}
/* =================================================== */
/* FALLBACK */
/* =================================================== */
/// @notice contract does not accept ETH donations
receive() external payable {
revert Errors.MultiVault_ReceiveNotAllowed();
}
/// @notice fallback function to decompress the calldata and call the appropriate function
fallback() external payable {
LibZip.cdFallback();
}
/* =================================================== */
/* RESTRICTED FUNCTIONS */
/* =================================================== */
/// @dev pauses the pausable contract methods
function pause() external onlyAdmin {
_pause();
}
/// @dev unpauses the pausable contract methods
function unpause() external onlyAdmin {
_unpause();
}
/// @dev schedule an operation to be executed after a delay
///
/// @param operationId unique identifier for the operation
/// @param data data to be executed
function scheduleOperation(bytes32 operationId, bytes calldata data) external onlyAdmin {
uint256 minDelay = generalConfig.minDelay;
// Generate the operation hash
bytes32 operationHash = keccak256(abi.encodePacked(operationId, data, minDelay));
// Check timelock constraints and schedule the operation
if (timelocks[operationHash].readyTime != 0) {
revert Errors.MultiVault_OperationAlreadyScheduled();
}
// calculate the time when the operation can be executed
uint256 readyTime = block.timestamp + minDelay;
timelocks[operationHash] = Timelock({data: data, readyTime: readyTime, executed: false});
}
/// @dev execute a scheduled operation
///
/// @param operationId unique identifier for the operation
/// @param data data to be executed
function cancelOperation(bytes32 operationId, bytes calldata data) external onlyAdmin {
// Generate the operation hash
bytes32 operationHash = keccak256(abi.encodePacked(operationId, data, generalConfig.minDelay));
// Check timelock constraints and cancel the operation
Timelock memory timelock = timelocks[operationHash];
if (timelock.readyTime == 0) {
revert Errors.MultiVault_OperationNotScheduled();
}
if (timelock.executed) {
revert Errors.MultiVault_OperationAlreadyExecuted();
}
delete timelocks[operationHash];
}
/// @dev set admin
/// @param admin address of the new admin
function setAdmin(address admin) external onlyAdmin {
// Generate the operation hash
bytes memory data = abi.encodeWithSelector(EthMultiVault.setAdmin.selector, admin);
bytes32 opHash = keccak256(abi.encodePacked(SET_ADMIN, data, generalConfig.minDelay));
// Check timelock constraints
_validateTimelock(opHash);
// Execute the operation
generalConfig.admin = admin;
// Mark the operation as executed
timelocks[opHash].executed = true;
}
/// @dev set protocol vault
/// @param protocolVault address of the new protocol vault
function setProtocolVault(address protocolVault) external onlyAdmin {
generalConfig.protocolVault = protocolVault;
}
/// @dev sets the minimum deposit amount for atoms and triples
/// @param minDeposit new minimum deposit amount
function setMinDeposit(uint256 minDeposit) external onlyAdmin {
generalConfig.minDeposit = minDeposit;
}
/// @dev sets the minimum share amount for atoms and triples
/// @param minShare new minimum share amount
function setMinShare(uint256 minShare) external onlyAdmin {
generalConfig.minShare = minShare;
}
/// @dev sets the atom URI max length
/// @param atomUriMaxLength new atom URI max length
function setAtomUriMaxLength(uint256 atomUriMaxLength) external onlyAdmin {
generalConfig.atomUriMaxLength = atomUriMaxLength;
}
/// @dev sets the atom share lock fee
/// @param atomWalletInitialDepositAmount new atom share lock fee
function setAtomWalletInitialDepositAmount(uint256 atomWalletInitialDepositAmount) external onlyAdmin {
atomConfig.atomWalletInitialDepositAmount = atomWalletInitialDepositAmount;
}
/// @dev sets the atom creation fee
/// @param atomCreationProtocolFee new atom creation fee
function setAtomCreationProtocolFee(uint256 atomCreationProtocolFee) external onlyAdmin {
atomConfig.atomCreationProtocolFee = atomCreationProtocolFee;
}
/// @dev sets fee charged in wei when creating a triple to protocol vault
/// @param tripleCreationProtocolFee new fee in wei
function setTripleCreationProtocolFee(uint256 tripleCreationProtocolFee) external onlyAdmin {
tripleConfig.tripleCreationProtocolFee = tripleCreationProtocolFee;
}
/// @dev sets the atom deposit fraction on triple creation used to increase the amount of assets
/// in the underlying atom vaults on triple creation
/// @param atomDepositFractionOnTripleCreation new atom deposit fraction on triple creation
function setAtomDepositFractionOnTripleCreation(uint256 atomDepositFractionOnTripleCreation) external onlyAdmin {
tripleConfig.atomDepositFractionOnTripleCreation = atomDepositFractionOnTripleCreation;
}
/// @dev sets the atom deposit fraction percentage for atoms used in triples
/// (number to be divided by `generalConfig.feeDenominator`)
/// @param atomDepositFractionForTriple new atom deposit fraction percentage
function setAtomDepositFractionForTriple(uint256 atomDepositFractionForTriple) external onlyAdmin {
tripleConfig.atomDepositFractionForTriple = atomDepositFractionForTriple;
}
/// @dev sets entry fees for the specified vault (id=0 sets the default fees for all vaults)
/// id = 0 changes the default entry fee, id = n changes fees for vault n specifically
/// @dev admin cannot set the entry fee to be greater than `maxEntryFeePercentage`, which is
/// set to be the 10% of `generalConfig.feeDenominator` (which represents 100%), to avoid
/// being able to prevent users from depositing assets with unreasonable fees
///
/// @param id vault id to set entry fee for
/// @param entryFee entry fee to set
function setEntryFee(uint256 id, uint256 entryFee) external onlyAdmin {
uint256 maxEntryFeePercentage = generalConfig.feeDenominator / 10;
if (entryFee > maxEntryFeePercentage) {
revert Errors.MultiVault_InvalidEntryFee();
}
vaultFees[id].entryFee = entryFee;
}
/// @dev sets exit fees for the specified vault (id=0 sets the default fees for all vaults)
/// id = 0 changes the default exit fee, id = n changes fees for vault n specifically
/// @dev admin cannot set the exit fee to be greater than `maxExitFeePercentage`, which is
/// set to be the 10% of `generalConfig.feeDenominator` (which represents 100%), to avoid
/// being able to prevent users from withdrawing their assets
///
/// @param id vault id to set exit fee for
/// @param exitFee exit fee to set
function setExitFee(uint256 id, uint256 exitFee) external onlyAdmin {
uint256 maxExitFeePercentage = generalConfig.feeDenominator / 10;
if (exitFee > maxExitFeePercentage) {
revert Errors.MultiVault_InvalidExitFee();
}
// Generate the operation hash
bytes memory data = abi.encodeWithSelector(EthMultiVault.setExitFee.selector, id, exitFee);
bytes32 opHash = keccak256(abi.encodePacked(SET_EXIT_FEE, data, generalConfig.minDelay));
// Check timelock constraints
_validateTimelock(opHash);
// Execute the operation
vaultFees[id].exitFee = exitFee;
// Mark the operation as executed
timelocks[opHash].executed = true;
}
/// @dev sets protocol fees for the specified vault (id=0 sets the default fees for all vaults)
/// id = 0 changes the default protocol fee, id = n changes fees for vault n specifically
/// @dev admin cannot set the protocol fee to be greater than `maxProtocolFeePercentage`, which is
/// set to be the 10% of `generalConfig.feeDenominator` (which represents 100%), to avoid
/// being able to prevent users from depositing or withdrawing their assets with unreasonable fees
///
/// @param id vault id to set protocol fee for
/// @param protocolFee protocol fee to set
function setProtocolFee(uint256 id, uint256 protocolFee) external onlyAdmin {
uint256 maxProtocolFeePercentage = generalConfig.feeDenominator / 10;
if (protocolFee > maxProtocolFeePercentage) {
revert Errors.MultiVault_InvalidProtocolFee();
}
vaultFees[id].protocolFee = protocolFee;
}
/// @dev sets the atomWarden address
/// @param atomWarden address of the new atomWarden
function setAtomWarden(address atomWarden) external onlyAdmin {
walletConfig.atomWarden = atomWarden;
}
/* =================================================== */
/* MUTATIVE FUNCTIONS */
/* =================================================== */
/* -------------------------- */
/* Atom Wallet */
/* -------------------------- */
/// @notice deploy a given atom wallet
/// @param atomId vault id of atom
/// @return atomWallet the address of the atom wallet
/// NOTE: deploys an ERC4337 account (atom wallet) through a BeaconProxy. Reverts if the atom vault does not exist
function deployAtomWallet(uint256 atomId) external whenNotPaused returns (address) {
if (atomId == 0 || atomId > count) {
revert Errors.MultiVault_VaultDoesNotExist();
}
// compute salt for create2
bytes32 salt = bytes32(atomId);
// get contract deployment data
bytes memory data = _getDeploymentData();
address atomWallet;
// deploy atom wallet with create2:
// value sent in wei,
// memory offset of `code` (after first 32 bytes where the length is),
// length of `code` (first 32 bytes of code),
// salt for create2
assembly {
atomWallet := create2(0, add(data, 0x20), mload(data), salt)
}
if (atomWallet == address(0)) {
revert Errors.MultiVault_DeployAccountFailed();
}
return atomWallet;
}
/* -------------------------- */
/* Create Atom */
/* -------------------------- */
/// @notice Create an atom and return its vault id
/// @param atomUri atom data to create atom with
/// @return id vault id of the atom
/// NOTE: This function will revert if called with less than `getAtomCost()` in `msg.value`
function createAtom(bytes calldata atomUri) external payable nonReentrant whenNotPaused returns (uint256) {
if (msg.value < getAtomCost()) {
revert Errors.MultiVault_InsufficientBalance();
}
// create atom and get the protocol deposit fee
(uint256 id, uint256 protocolDepositFee) = _createAtom(atomUri, msg.value);
uint256 totalFeesForProtocol = atomConfig.atomCreationProtocolFee + protocolDepositFee;
_transferFeesToProtocolVault(totalFeesForProtocol);
return id;
}
/// @notice Batch create atoms and return their vault ids
/// @param atomUris atom data array to create atoms with
/// @return ids vault ids array of the atoms
/// NOTE: This function will revert if called with less than `getAtomCost()` * `atomUris.length` in `msg.value`
function batchCreateAtom(bytes[] calldata atomUris)
external
payable
nonReentrant
whenNotPaused
returns (uint256[] memory)
{
uint256 length = atomUris.length;
if (msg.value < getAtomCost() * length) {
revert Errors.MultiVault_InsufficientBalance();
}
uint256 valuePerAtom = msg.value / length;
uint256 protocolDepositFeeTotal;
uint256[] memory ids = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
uint256 protocolDepositFee;
(ids[i], protocolDepositFee) = _createAtom(atomUris[i], valuePerAtom);
// add protocol deposit fees to total
protocolDepositFeeTotal += protocolDepositFee;
}
uint256 totalFeesForProtocol = atomConfig.atomCreationProtocolFee * length + protocolDepositFeeTotal;
_transferFeesToProtocolVault(totalFeesForProtocol);
return ids;
}
/// @notice Internal utility function to create an atom and handle vault creation
///
/// @param atomUri The atom data to create an atom with
/// @param value The value sent with the transaction
///
/// @return id The new vault ID created for the atom
function _createAtom(bytes calldata atomUri, uint256 value) internal returns (uint256, uint256) {
if (atomUri.length > generalConfig.atomUriMaxLength) {
revert Errors.MultiVault_AtomUriTooLong();
}
uint256 atomCost = getAtomCost();
// check if atom already exists based on hash
bytes32 hash = keccak256(atomUri);
if (atomsByHash[hash] != 0) {
revert Errors.MultiVault_AtomExists(atomUri);
}
// calculate user deposit amount
uint256 userDeposit = value - atomCost;
// create a new atom vault
uint256 id = _createVault();
// calculate protocol deposit fee
uint256 protocolDepositFee = protocolFeeAmount(userDeposit, id);
// calculate user deposit after protocol fees
uint256 userDepositAfterprotocolFee = userDeposit - protocolDepositFee;
// deposit user funds into vault and mint shares for the user and shares for the zero address
_depositOnVaultCreation(
id,
msg.sender, // receiver
userDepositAfterprotocolFee
);
// get atom wallet address for the corresponding atom
address atomWallet = computeAtomWalletAddr(id);
// deposit atomWalletInitialDepositAmount amount of assets and mint the shares for the atom wallet
_depositOnVaultCreation(
id,
atomWallet, // receiver
atomConfig.atomWalletInitialDepositAmount
);
// map the new vault ID to the atom data
atoms[id] = atomUri;
// map the resultant atom hash to the new vault ID
atomsByHash[hash] = id;
emit AtomCreated(msg.sender, atomWallet, atomUri, id);
return (id, protocolDepositFee);
}
/* -------------------------- */
/* Create Triple */
/* -------------------------- */
/// @notice create a triple and return its vault id
///
/// @param subjectId vault id of the subject atom
/// @param predicateId vault id of the predicate atom
/// @param objectId vault id of the object atom
///
/// @return id vault id of the triple
/// NOTE: This function will revert if called with less than `getTripleCost()` in `msg.value`.
/// This function will revert if any of the atoms do not exist or if any ids are triple vaults.
function createTriple(uint256 subjectId, uint256 predicateId, uint256 objectId)
external
payable
nonReentrant
whenNotPaused
returns (uint256)
{
if (msg.value < getTripleCost()) {
revert Errors.MultiVault_InsufficientBalance();
}
// create triple and get the protocol deposit fee
(uint256 id, uint256 protocolDepositFee) = _createTriple(subjectId, predicateId, objectId, msg.value);
uint256 totalFeesForProtocol = tripleConfig.tripleCreationProtocolFee + protocolDepositFee;
_transferFeesToProtocolVault(totalFeesForProtocol);
return id;
}
/// @notice batch create triples and return their vault ids
/// @param subjectIds vault ids array of subject atoms
/// @param predicateIds vault ids array of predicate atoms
/// @param objectIds vault ids array of object atoms
/// NOTE: This function will revert if called with less than `getTripleCost()` * `array.length` in `msg.value`.
/// This function will revert if any of the atoms do not exist or if any ids are triple vaults.
function batchCreateTriple(
uint256[] calldata subjectIds,
uint256[] calldata predicateIds,
uint256[] calldata objectIds
) external payable nonReentrant whenNotPaused returns (uint256[] memory) {
if (subjectIds.length != predicateIds.length || subjectIds.length != objectIds.length) {
revert Errors.MultiVault_ArraysNotSameLength();
}
uint256 length = subjectIds.length;
uint256 tripleCost = getTripleCost();
if (msg.value < tripleCost * length) {
revert Errors.MultiVault_InsufficientBalance();
}
uint256 valuePerTriple = msg.value / length;
uint256 protocolDepositFeeTotal;
uint256[] memory ids = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
uint256 protocolDepositFee;
(ids[i], protocolDepositFee) = _createTriple(subjectIds[i], predicateIds[i], objectIds[i], valuePerTriple);
// add protocol deposit fees to total
protocolDepositFeeTotal += protocolDepositFee;
}
uint256 totalFeesForProtocol = tripleConfig.tripleCreationProtocolFee * length + protocolDepositFeeTotal;
_transferFeesToProtocolVault(totalFeesForProtocol);
return ids;
}
/// @notice Internal utility function to create a triple
///
/// @param subjectId vault id of the subject atom
/// @param predicateId vault id of the predicate atom
/// @param objectId vault id of the object atom
/// @param value The amount of ETH the user has sent minus the base triple cost
///
/// @return id The new vault ID of the created triple
/// @return protocolDepositFee The calculated protocol fee for the deposit
function _createTriple(uint256 subjectId, uint256 predicateId, uint256 objectId, uint256 value)
internal
returns (uint256, uint256)
{
uint256[3] memory tripleAtomIds = [subjectId, predicateId, objectId];
for (uint256 i = 0; i < 3; i++) {
// make sure atoms exist, if not, revert
if (tripleAtomIds[i] == 0 || tripleAtomIds[i] > count) {
revert Errors.MultiVault_AtomDoesNotExist(tripleAtomIds[i]);
}
// make sure that each id is not a triple vault id
if (isTripleId(tripleAtomIds[i])) {
revert Errors.MultiVault_VaultIsTriple(tripleAtomIds[i]);
}
}
// check if triple already exists
bytes32 hash = tripleHashFromAtoms(subjectId, predicateId, objectId);
if (triplesByHash[hash] != 0) {
revert Errors.MultiVault_TripleExists(subjectId, predicateId, objectId);
}
// calculate user deposit amount
uint256 userDeposit = value - getTripleCost();
// create a new positive triple vault
uint256 id = _createVault();
// calculate protocol deposit fee
uint256 protocolDepositFee = protocolFeeAmount(userDeposit, id);
// calculate user deposit after protocol fees
uint256 userDepositAfterprotocolFee = userDeposit - protocolDepositFee;
// map the resultant triple hash to the new vault ID of the triple
triplesByHash[hash] = id;
// map the triple's vault ID to the underlying atom vault IDs
triples[id] = [subjectId, predicateId, objectId];
// set this new triple's vault ID as true in the IsTriple mapping as well as its counter
isTriple[id] = true;
uint256 atomDepositFraction = atomDepositFractionAmount(userDepositAfterprotocolFee, id);
// give the user shares in the positive triple vault
_depositOnVaultCreation(
id,
msg.sender, // receiver
userDepositAfterprotocolFee - atomDepositFraction
);
// deposit assets into each underlying atom vault and mint shares for the receiver
if (atomDepositFraction > 0) {
_depositAtomFraction(
id,
msg.sender, // receiver
atomDepositFraction
);
}
if (tripleConfig.atomDepositFractionOnTripleCreation > 0) {
for (uint256 i = 0; i < 3; i++) {
uint256 atomId = tripleAtomIds[i];
// increase the total assets in each underlying atom vault
_setVaultTotals(
atomId,
vaults[atomId].totalAssets + (tripleConfig.atomDepositFractionOnTripleCreation / 3),
vaults[atomId].totalShares
);
}
}
emit TripleCreated(msg.sender, subjectId, predicateId, objectId, id);
return (id, protocolDepositFee);
}
/* -------------------------- */
/* Deposit/Redeem Atom */
/* -------------------------- */
/// @notice deposit eth into an atom vault and grant ownership of 'shares' to 'reciever'
/// *payable msg.value amount of eth to deposit
/// @dev assets parameter is omitted in favor of msg.value, unlike in ERC4626
///
/// @param receiver the address to receive the shares
/// @param id the vault ID of the atom
///
/// @return shares the amount of shares minted
/// NOTE: this function will revert if the minimum deposit amount of eth is not met and
/// if the vault ID does not exist/is not an atom.
function depositAtom(address receiver, uint256 id) external payable nonReentrant whenNotPaused returns (uint256) {
if (id == 0 || id > count) {
revert Errors.MultiVault_VaultDoesNotExist();
}
if (isTripleId(id)) {
revert Errors.MultiVault_VaultNotAtom();
}
if (msg.value < generalConfig.minDeposit) {
revert Errors.MultiVault_MinimumDeposit();
}
uint256 protocolFee = protocolFeeAmount(msg.value, id);
uint256 userDepositAfterprotocolFee = msg.value - protocolFee;
// deposit eth into vault and mint shares for the receiver
uint256 shares = _deposit(receiver, id, userDepositAfterprotocolFee);
_transferFeesToProtocolVault(protocolFee);
return shares;
}
/// @notice redeem assets from an atom vault
///
/// @param shares the amount of shares to redeem
/// @param receiver the address to receiver the assets
/// @param id the vault ID of the atom
///
/// @return assets the amount of assets/eth withdrawn
/// NOTE: Emergency redemptions without any fees being charged are always possible, even if the contract is paused
/// See `getRedeemAssetsAndFees` for more details on the fees charged
function redeemAtom(uint256 shares, address receiver, uint256 id) external nonReentrant returns (uint256) {
if (id == 0 || id > count) {
revert Errors.MultiVault_VaultDoesNotExist();
}
if (isTripleId(id)) {
revert Errors.MultiVault_VaultNotAtom();
}
/*
withdraw shares from vault, returning the amount of
assets to be transferred to the receiver
*/
(uint256 assets, uint256 protocolFee) = _redeem(id, msg.sender, shares);
// transfer eth to receiver factoring in fees/shares
(bool success,) = payable(receiver).call{value: assets}("");
if (!success) {
revert Errors.MultiVault_TransferFailed();
}
_transferFeesToProtocolVault(protocolFee);
return assets;
}
/* -------------------------- */
/* Deposit/Redeem Triple */
/* -------------------------- */
/// @notice deposits assets of underlying tokens into a triple vault and grants ownership of 'shares' to 'receiver'
/// *payable msg.value amount of eth to deposit
/// @dev assets parameter is omitted in favor of msg.value, unlike in ERC4626
///
/// @param receiver the address to receive the shares
/// @param id the vault ID of the triple
///
/// @return shares the amount of shares minted
/// NOTE: this function will revert if the minimum deposit amount of eth is not met and
/// if the vault ID does not exist/is not a triple.
function depositTriple(address receiver, uint256 id)
external
payable
nonReentrant
whenNotPaused
returns (uint256)
{
if (!isTripleId(id)) {
revert Errors.MultiVault_VaultNotTriple();
}
if (_hasCounterStake(id, receiver)) {
revert Errors.MultiVault_HasCounterStake();
}
if (msg.value < generalConfig.minDeposit) {
revert Errors.MultiVault_MinimumDeposit();
}
uint256 protocolFee = protocolFeeAmount(msg.value, id);
uint256 userDepositAfterprotocolFee = msg.value - protocolFee;
// deposit eth into vault and mint shares for the receiver
uint256 shares = _deposit(receiver, id, userDepositAfterprotocolFee);
_transferFeesToProtocolVault(protocolFee);
// distribute atom shares for all 3 atoms that underly the triple
uint256 atomDepositFraction = atomDepositFractionAmount(userDepositAfterprotocolFee, id);
_depositAtomFraction(id, receiver, atomDepositFraction);
return shares;
}
/// @notice redeems 'shares' number of shares from the triple vault and send 'assets' eth
/// from the multiVault to 'reciever' factoring in exit fees
///
/// @param shares the amount of shares to redeem
/// @param receiver the address to receiver the assets
/// @param id the vault ID of the triple
///
/// @return assets the amount of assets/eth withdrawn
/// NOTE: Emergency redemptions without any fees being charged are always possible, even if the contract is paused
/// See `getRedeemAssetsAndFees` for more details on the fees charged
function redeemTriple(uint256 shares, address receiver, uint256 id) external nonReentrant returns (uint256) {
if (!isTripleId(id)) {
revert Errors.MultiVault_VaultNotTriple();
}
/*
withdraw shares from vault, returning the amount of
assets to be transferred to the receiver
*/
(uint256 assets, uint256 protocolFee) = _redeem(id, msg.sender, shares);
// transfer eth to receiver factoring in fees/shares
(bool success,) = payable(receiver).call{value: assets}("");
if (!success) {
revert Errors.MultiVault_TransferFailed();
}
_transferFeesToProtocolVault(protocolFee);
return assets;
}
/* =================================================== */
/* INTERNAL METHODS */
/* =================================================== */
/// @dev transfer fees to the protocol vault
function _transferFeesToProtocolVault(uint256 value) internal {
if (value == 0) return;
(bool success,) = payable(generalConfig.protocolVault).call{value: value}("");
if (!success) {
revert Errors.MultiVault_TransferFailed();
}
emit FeesTransferred(msg.sender, generalConfig.protocolVault, value);
}
/// @dev divides amount across the three atoms composing the triple and issues shares to
/// the receiver. Doesn't charge additional protocol fees, but it does charge entry fees on each deposit
/// into an atom vault.
///
/// @param id the vault ID of the triple
/// @param receiver the address to receive the shares
/// @param amount the amount of eth to deposit
/// NOTE: assumes funds have already been transferred to this contract
function _depositAtomFraction(uint256 id, address receiver, uint256 amount) internal {
// load atom IDs
uint256[3] memory atomsIds;
(atomsIds[0], atomsIds[1], atomsIds[2]) = getTripleAtoms(id);
// floor div, so perAtom is slightly less than 1/3 of total input amount
uint256 perAtom = amount / 3;
// distribute proportional shares to each atom
for (uint256 i = 0; i < 3; i++) {
// deposit assets into each atom vault and mint shares for the receiver
uint256 shares = _deposit(receiver, atomsIds[i], perAtom);
// update the mapping which tracks atom shares
tripleAtomShares[id][atomsIds[i]][receiver] += shares;
}
}
/// @dev deposit assets into a vault upon creation.
/// Changes the vault's total assets, total shares and balanceOf mappings to reflect the deposit.
/// Additionally, initializes a counter vault with ghost shares.
///
/// @param id the vault ID of the atom or triple
/// @param receiver the address to receive the shares
/// @param assets the amount of eth to deposit
function _depositOnVaultCreation(uint256 id, address receiver, uint256 assets) internal {
bool isAtomWallet = receiver == computeAtomWalletAddr(id);
// ghost shares minted to the zero address upon vault creation
uint256 sharesForZeroAddress = generalConfig.minShare;
// ghost shares for the counter vault
uint256 assetsForZeroAddressInCounterVault = generalConfig.minShare;
uint256 sharesForReceiver = assets;
// changes in vault's total assets or total shares
uint256 totalDelta = isAtomWallet ? sharesForReceiver : sharesForReceiver + sharesForZeroAddress;
// set vault totals for the vault
_setVaultTotals(id, vaults[id].totalAssets + totalDelta, vaults[id].totalShares + totalDelta);
// mint `sharesOwed` shares to sender factoring in fees
_mint(receiver, id, sharesForReceiver);
// mint `sharesForZeroAddress` shares to zero address to initialize the vault
if (!isAtomWallet) {
_mint(address(0), id, sharesForZeroAddress);
}
/// Initialize the counter triple vault with ghost shares if it is a triple creation flow
if (isTripleId(id)) {
uint256 counterVaultId = getCounterIdFromTriple(id);
// set vault totals
_setVaultTotals(
counterVaultId,
vaults[counterVaultId].totalAssets + assetsForZeroAddressInCounterVault,
vaults[counterVaultId].totalShares + sharesForZeroAddress
);
// mint `sharesForZeroAddress` shares to zero address to initialize the vault
_mint(address(0), counterVaultId, sharesForZeroAddress);
}
emit Deposited(
msg.sender,
receiver,
vaults[id].balanceOf[receiver],
assets, // userAssetsAfterTotalFees
totalDelta, // sharesForReceiver
0, // entryFee is not charged on vault creation
id
);
}
/// @notice Internal function to encapsulate the common deposit logic for both atoms and triples
///
/// @param receiver the address to receive the shares
/// @param id the vault ID of the atom or triple
/// @param value the amount of eth to deposit
///
/// @return sharesForReceiver the amount of shares minted
function _deposit(address receiver, uint256 id, uint256 value) internal returns (uint256) {
if (previewDeposit(value, id) == 0) {
revert Errors.MultiVault_DepositOrWithdrawZeroShares();
}
(uint256 totalAssetsDelta, uint256 sharesForReceiver, uint256 userAssetsAfterTotalFees, uint256 entryFee) =
getDepositSharesAndFees(value, id);
if (totalAssetsDelta <= 0) {
revert Errors.MultiVault_InsufficientDepositAmountToCoverFees();
}
uint256 totalSharesDelta = sharesForReceiver;
// set vault totals (assets and shares)
_setVaultTotals(id, vaults[id].totalAssets + totalAssetsDelta, vaults[id].totalShares + totalSharesDelta);
// mint `sharesOwed` shares to sender factoring in fees
_mint(receiver, id, sharesForReceiver);
emit Deposited(
msg.sender,
receiver,
vaults[id].balanceOf[receiver],
userAssetsAfterTotalFees,
sharesForReceiver,
entryFee,
id
);
return sharesForReceiver;
}
/// @dev redeem shares out of a given vault.
/// Changes the vault's total assets, total shares and balanceOf mappings to reflect the withdrawal
///
/// @return assetsForReceiver the amount of assets/eth to be transferred to the receiver
/// @return protocolFee the amount of protocol fees deducted
function _redeem(uint256 id, address owner, uint256 shares) internal returns (uint256, uint256) {
if (shares == 0) {
revert Errors.MultiVault_DepositOrWithdrawZeroShares();
}
if (vaults[id].balanceOf[msg.sender] < shares) {
revert Errors.MultiVault_InsufficientSharesInVault();
}
uint256 remainingShares = vaults[id].totalShares - shares;
if (remainingShares < generalConfig.minShare) {
revert Errors.MultiVault_InsufficientRemainingSharesInVault(remainingShares);
}
(, uint256 assetsForReceiver, uint256 protocolFee, uint256 exitFee) = getRedeemAssetsAndFees(shares, id);
// set vault totals (assets and shares)
_setVaultTotals(
id,
vaults[id].totalAssets - (assetsForReceiver + protocolFee), // totalAssetsDelta
vaults[id].totalShares - shares // totalSharesDelta
);
// burn shares, then transfer assets to receiver
_burn(owner, id, shares);
emit Redeemed(msg.sender, owner, vaults[id].balanceOf[owner], assetsForReceiver, shares, exitFee, id);
return (assetsForReceiver, protocolFee);
}
/// @dev mint vault shares of vault ID `id` to address `to`
///
/// @param to address to mint shares to
/// @param id vault ID to mint shares for
/// @param amount amount of shares to mint
function _mint(address to, uint256 id, uint256 amount) internal {
vaults[id].balanceOf[to] += amount;
}