-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDefifaDelegate.sol
1089 lines (885 loc) · 50.1 KB
/
DefifaDelegate.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: MIT
pragma solidity ^0.8.16;
import {PRBMath} from "@paulrberg/contracts/math/PRBMath.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Checkpoints} from "@openzeppelin/contracts/utils/Checkpoints.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {JBFundingCycleMetadataResolver} from
"@jbx-protocol/juice-contracts-v3/contracts/libraries/JBFundingCycleMetadataResolver.sol";
import {JBRedeemParamsData} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBRedeemParamsData.sol";
import {JBDidRedeemData} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBDidRedeemData.sol";
import {JBDidPayData} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBDidPayData.sol";
import {JBRedemptionDelegateAllocation} from
"@jbx-protocol/juice-contracts-v3/contracts/structs/JBRedemptionDelegateAllocation.sol";
import {JBFundingCycle} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBFundingCycle.sol";
import {IJBFundingCycleStore} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBFundingCycleStore.sol";
import {IJBSplitAllocator} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBSplitAllocator.sol";
import {IJBDirectory} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBDirectory.sol";
import {IJBPaymentTerminal} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBPaymentTerminal.sol";
import {ERC721} from "@jbx-protocol/juice-721-delegate/contracts/abstract/ERC721.sol";
import {JB721Delegate} from "@jbx-protocol/juice-721-delegate/contracts/abstract/JB721Delegate.sol";
import {IJB721TokenUriResolver} from "@jbx-protocol/juice-721-delegate/contracts/interfaces/IJB721TokenUriResolver.sol";
import {IJBTiered721DelegateStore} from
"@jbx-protocol/juice-721-delegate/contracts/interfaces/IJBTiered721DelegateStore.sol";
import {JBTiered721FundingCycleMetadataResolver} from
"@jbx-protocol/juice-721-delegate/contracts/libraries/JBTiered721FundingCycleMetadataResolver.sol";
import {JB721TierParams} from "@jbx-protocol/juice-721-delegate/contracts/structs/JB721TierParams.sol";
import {JB721Tier} from "@jbx-protocol/juice-721-delegate/contracts/structs/JB721Tier.sol";
import {JBTiered721MintReservesForTiersData} from
"@jbx-protocol/juice-721-delegate/contracts/structs/JBTiered721MintReservesForTiersData.sol";
import {JBTiered721SetTierDelegatesData} from
"@jbx-protocol/juice-721-delegate/contracts/structs/JBTiered721SetTierDelegatesData.sol";
import {IDefifaDelegate} from "./interfaces/IDefifaDelegate.sol";
import {IDefifaGamePhaseReporter} from "./interfaces/IDefifaGamePhaseReporter.sol";
import {IDefifaGamePotReporter} from "./interfaces/IDefifaGamePotReporter.sol";
import {DefifaTierRedemptionWeight} from "./structs/DefifaTierRedemptionWeight.sol";
import {DefifaGamePhase} from "./enums/DefifaGamePhase.sol";
/// @title DefifaDelegate
/// @notice A delegate that transforms Juicebox treasury interactions into a Defifa game.
contract DefifaDelegate is JB721Delegate, Ownable, IDefifaDelegate {
using Checkpoints for Checkpoints.History;
//*********************************************************************//
// --------------------------- custom errors ------------------------- //
//*********************************************************************//
error BAD_TIER_ORDER();
error DELEGATE_ADDRESS_ZERO();
error DELEGATE_CHANGES_UNAVAILABLE_IN_THIS_PHASE();
error GAME_ISNT_SCORING_YET();
error INVALID_TIER_ID();
error INVALID_REDEMPTION_WEIGHTS();
error NOTHING_TO_CLAIM();
error NOTHING_TO_MINT();
error WRONG_CURRENCY();
error NO_CONTEST();
error OVERSPENDING();
error REDEMPTION_WEIGHTS_ALREADY_SET();
error RESERVED_TOKEN_MINTING_PAUSED();
error TRANSFERS_PAUSED();
error UNAUTHORIZED();
//*********************************************************************//
// --------------------- public constant properties ------------------ //
//*********************************************************************//
/// @notice
/// The total redemption weight that can be divided among tiers.
uint256 public constant override TOTAL_REDEMPTION_WEIGHT = 1_000_000_000_000_000_000;
//*********************************************************************//
// -------------------- internal stored properties ------------------- //
//*********************************************************************//
/// @notice The redemption weight for each tier.
/// @dev Tiers are limited to ID 128
uint256[128] internal _tierRedemptionWeights;
/// @notice The delegation status for each address and for each tier.
/// _delegator The delegator.
/// _tierId The ID of the tier being delegated.
mapping(address => mapping(uint256 => address)) internal _tierDelegation;
/// @notice The delegation checkpoints for each address and for each tier.
/// _delegator The delegator.
/// _tierId The ID of the tier being checked.
mapping(address => mapping(uint256 => Checkpoints.History)) internal _delegateTierCheckpoints;
/// @notice The total delegation status for each tier.
/// _tierId The ID of the tier being checked.
mapping(uint256 => Checkpoints.History) internal _totalTierCheckpoints;
/// @notice The amount of $DEFIFA and $BASE_PROTOCOL tokens this game was allocated from paying the network fee, packed into a uint256.
uint256 internal _packedTokenAllocation;
/// @notice The first owner of each token ID, stored on first transfer out.
/// _tokenId The ID of the token to get the stored first owner of.
mapping(uint256 => address) internal _firstOwnerOf;
/// @notice The names of each tier.
/// @dev _tierId The ID of the tier to get a name for.
mapping(uint256 => string) internal _tierNameOf;
//*********************************************************************//
// ---------------- public immutable stored properties --------------- //
//*********************************************************************//
/// @notice The $DEFIFA token that is expected to be issued from paying fees.
IERC20 public immutable override defifaToken;
/// @notice The $BASE_PROTOCOL token that is expected to be issued from paying fees.
IERC20 public immutable override baseProtocolToken;
//*********************************************************************//
// --------------------- public stored properties -------------------- //
//*********************************************************************//
/// @notice The address of the origin 'DefifaDelegate', used to check in the init if the contract is the original or not
address public immutable override codeOrigin;
/// @notice The contract that stores and manages the NFT's data.
IJBTiered721DelegateStore public override store;
/// @notice The contract storing all funding cycle configurations.
IJBFundingCycleStore public override fundingCycleStore;
/// @notice The contract reporting game phases.
IDefifaGamePhaseReporter public override gamePhaseReporter;
/// @notice The contract reporting the game pot.
IDefifaGamePotReporter public override gamePotReporter;
/// @notice The currency that is accepted when minting tier NFTs.
uint256 public override pricingCurrency;
/// @notice A flag indicating if the redemption weight has been set.
bool public override redemptionWeightIsSet;
/// @notice The common base for the tokenUri's
string public override baseURI;
/// @notice Contract metadata uri.
string public override contractURI;
/// @notice The address that'll be set as the attestation delegate by default.
address public override defaultAttestationDelegate;
/// @notice The amount that has been redeemed from ths game, refunds are not counted.
uint256 public override amountRedeemed;
/// @notice The amount of tokens that have been redeemed from a tier, refunds are not counted.
/// @custom:param The tier from which tokens have been redeemed.
mapping(uint256 => uint256) public override tokensRedeemedFrom;
//*********************************************************************//
// ------------------------- external views -------------------------- //
//*********************************************************************//
/// @notice The name of the NFT.
/// @return The name of the NFT.
function name() public view override(ERC721, IDefifaDelegate) returns (string memory) {
return super.name();
}
/// @notice The redemption weight for each tier.
/// @return The array of weights, indexed by tier.
function tierRedemptionWeights() external view override returns (uint256[128] memory) {
return _tierRedemptionWeights;
}
/// @notice Returns the delegate of an account for specific tier.
/// @param _account The account to check for a delegate of.
/// @param _tier the tier to check within.
function getTierDelegateOf(address _account, uint256 _tier) external view override returns (address) {
return _tierDelegation[_account][_tier];
}
/// @notice Returns the current attestation power of an address for a specific tier.
/// @param _account The address to check.
/// @param _tier The tier to check within.
function getTierAttestationUnitsOf(address _account, uint256 _tier) external view override returns (uint256) {
return _delegateTierCheckpoints[_account][_tier].latest();
}
/// @notice Returns the past attestation units of a specific address for a specific tier.
/// @param _account The address to check.
/// @param _tier The tier to check within.
/// @param _blockNumber the blocknumber to check the attestation power at.
function getPastTierAttestationUnitsOf(address _account, uint256 _tier, uint256 _blockNumber)
external
view
override
returns (uint256)
{
return _delegateTierCheckpoints[_account][_tier].getAtBlock(_blockNumber);
}
/// @notice Returns the total amount of attestation units that exists for a tier.
/// @param _tier The tier to check.
function getTierTotalAttestationUnitsOf(uint256 _tier) external view override returns (uint256) {
return _totalTierCheckpoints[_tier].latest();
}
/// @notice Returns the total amount of attestation units that has existed for a tier.
/// @param _tier The tier to check.
/// @param _blockNumber The blocknumber to check the total attestation units at.
function getPastTierTotalAttestationUnitsOf(uint256 _tier, uint256 _blockNumber)
external
view
override
returns (uint256)
{
return _totalTierCheckpoints[_tier].getAtBlock(_blockNumber);
}
/// @notice The first owner of each token ID, which corresponds to the address that originally contributed to the project to receive the NFT.
/// @param _tokenId The ID of the token to get the first owner of.
/// @return The first owner of the token.
function firstOwnerOf(uint256 _tokenId) external view override returns (address) {
// Get a reference to the first owner.
address _storedFirstOwner = _firstOwnerOf[_tokenId];
// If the stored first owner is set, return it.
if (_storedFirstOwner != address(0)) return _storedFirstOwner;
// Otherwise, the first owner must be the current owner.
return _owners[_tokenId];
}
/// @notice The name of the tier with the specified ID.
function tierNameOf(uint256 _tierId) external view override returns (string memory) {
return _tierNameOf[_tierId];
}
//*********************************************************************//
// -------------------------- public views --------------------------- //
//*********************************************************************//
/// @notice The total number of tokens owned by the given owner across all tiers.
/// @param _owner The address to check the balance of.
/// @return balance The number of tokens owned by the owner across all tiers.
function balanceOf(address _owner) public view override returns (uint256 balance) {
return store.balanceOf(address(this), _owner);
}
/// @notice The metadata URI of the provided token ID.
/// @dev Defer to the tokenUriResolver if set, otherwise, use the tokenUri set with the token's tier.
/// @param _tokenId The ID of the token to get the tier URI for.
/// @return The token URI corresponding with the tier or the tokenUriResolver URI.
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
// Use the resolver.
return store.tokenUriResolverOf(address(this)).tokenUriOf(address(this), _tokenId);
}
/// @notice The cumulative weight the given token IDs have in redemptions compared to the `_totalRedemptionWeight`.
/// @param _tokenIds The IDs of the tokens to get the cumulative redemption weight of.
/// @return cumulativeWeight The weight.
function redemptionWeightOf(uint256[] memory _tokenIds, JBRedeemParamsData calldata)
public
view
virtual
override
returns (uint256 cumulativeWeight)
{
// Keep a reference to the number of tokens being redeemed.
uint256 _tokenCount = _tokenIds.length;
for (uint256 _i; _i < _tokenCount;) {
// Calculate what percentage of the tier redemption amount a single token counts for.
cumulativeWeight += redemptionWeightOf(_tokenIds[_i]);
unchecked {
++_i;
}
}
}
/// @notice The weight the given token ID has in redemptions.
/// @param _tokenId The ID of the token to get the redemption weight of.
/// @return The weight.
function redemptionWeightOf(uint256 _tokenId) public view override returns (uint256) {
// Keep a reference to the token's tier ID.
uint256 _tierId = store.tierIdOfToken(_tokenId);
// Keep a reference to the tier.
JB721Tier memory _tier = store.tierOf(address(this), _tierId, false);
// Get the tier's weight.
uint256 _weight = _tierRedemptionWeights[_tierId - 1];
// If there's no weight there's nothing to redeem.
if (_weight == 0) return 0;
// If no tiers were minted, nothing to redeem.
if (_tier.initialQuantity - _tier.remainingQuantity == 0) return 0;
// Calculate the percentage of the tier redemption amount a single token counts for.
return _weight / (_tier.initialQuantity - _tier.remainingQuantity + tokensRedeemedFrom[_tierId]);
}
/// @notice The cumulative weight that all token IDs have in redemptions.
/// @return The total weight.
function totalRedemptionWeight(JBRedeemParamsData calldata) public view virtual override returns (uint256) {
return TOTAL_REDEMPTION_WEIGHT;
}
/// @notice The amount of $DEFIFA and $BASE_PROTOCOL tokens this game was allocated from paying the network fee.
/// @return defifaTokenAllocation The $DEFIFA token allocation.
/// @return baseProtocolTokenAllocation The $BASE_PROTOCOL token allocation.
function tokenAllocations()
public
view
returns (uint256 defifaTokenAllocation, uint256 baseProtocolTokenAllocation)
{
// Get a reference to the pakced token allocation.
uint256 _packed = _packedTokenAllocation;
// defifa token allocation in bits 0-127 (128 bits).
uint256 _defifaTokenAllocation = uint256(uint128(_packed));
// base protocol token allocation in bits 128-255 (128 bits).
uint256 _baseProtocolTokenAllocation = uint256(uint128(_packed >> 128));
// Return the values.
defifaTokenAllocation =
(_defifaTokenAllocation != 0) ? _defifaTokenAllocation : defifaToken.balanceOf(address(this));
baseProtocolTokenAllocation = (_baseProtocolTokenAllocation != 0)
? _baseProtocolTokenAllocation
: baseProtocolToken.balanceOf(address(this));
}
/// @notice Part of IJBFundingCycleDataSource, this function gets called when a project's token holders redeem.
/// @param _data The Juicebox standard project redemption data.
/// @return reclaimAmount The amount that should be reclaimed from the treasury.
/// @return memo The memo that should be forwarded to the event.
/// @return delegateAllocations The amount to send to delegates instead of adding to the beneficiary.
function redeemParams(JBRedeemParamsData calldata _data)
public
view
override
returns (uint256 reclaimAmount, string memory memo, JBRedemptionDelegateAllocation[] memory delegateAllocations)
{
// Make sure fungible project tokens aren't being redeemed too.
if (_data.tokenCount > 0) revert UNEXPECTED_TOKEN_REDEEMED();
// Check the 4 bytes interfaceId and handle the case where the metadata was not intended for this contract
// Skip 32 bytes reserved for generic extension parameters.
if (_data.metadata.length < 36 || bytes4(_data.metadata[32:36]) != type(IDefifaDelegate).interfaceId) {
revert INVALID_REDEMPTION_METADATA();
}
// Set the only delegate allocation to be a callback to this contract.
delegateAllocations = new JBRedemptionDelegateAllocation[](1);
delegateAllocations[0] = JBRedemptionDelegateAllocation(this, 0);
// Decode the metadata
(,, uint256[] memory _decodedTokenIds) = abi.decode(_data.metadata, (bytes32, bytes4, uint256[]));
// Get the current gae phase.
DefifaGamePhase _gamePhase = gamePhaseReporter.currentGamePhaseOf(_data.projectId);
// If the game is in its minting, refund, or no contest phase, reclaim amount is the same as it costed to mint.
if (
_gamePhase == DefifaGamePhase.MINT || _gamePhase == DefifaGamePhase.REFUND
|| _gamePhase == DefifaGamePhase.NO_CONTEST || _gamePhase == DefifaGamePhase.NO_CONTEST_INEVITABLE
) {
// Keep a reference to the number of tokens.
uint256 _numberOfTokenIds = _decodedTokenIds.length;
for (uint256 _i; _i < _numberOfTokenIds;) {
unchecked {
reclaimAmount += store.tierOfTokenId(address(this), _decodedTokenIds[_i], false).price;
_i++;
}
}
return (reclaimAmount, _data.memo, delegateAllocations);
}
// Return the weighted amount.
return (
PRBMath.mulDiv(
_data.overflow + amountRedeemed, redemptionWeightOf(_decodedTokenIds, _data), TOTAL_REDEMPTION_WEIGHT
),
_data.memo,
delegateAllocations
);
}
/// @notice The amount of $DEFIFA and $BASE_PROTOCOL tokens claimable for a set of token IDs.
/// @param _tokenIds The IDs of the tokens that justify a $DEFIFA claim.
/// @return defifaTokenAmount The amount of $DEFIFA that can be claimed.
/// @return baseProtocolTokenAmount The amount of $BASE_PROTOCOL that can be claimed.
function tokensClaimableFor(uint256[] memory _tokenIds)
public
view
returns (uint256 defifaTokenAmount, uint256 baseProtocolTokenAmount)
{
// Set the amount of total $DEFIFA and $BASE_PROTOCOL token allocation if it hasn't been set yet.
(uint256 _defifaTokenAllocation, uint256 _baseProtocolTokenAllocation) = tokenAllocations();
// If there's no $DEFIFA in this contract, return 0.
if (_defifaTokenAllocation == 0 && _baseProtocolTokenAllocation == 0) return (0, 0);
// Get a reference to the game's current pot, including any fulfilled commitments.
(uint256 _pot,,) = gamePotReporter.currentGamePotOf(projectId, true);
// If there's no usable pot left, the rest of the $DEFIFA and $BASE_PROTOCOL is available.
if (_pot - gamePotReporter.fulfilledCommitmentsOf(projectId) == 0) {
defifaTokenAmount = defifaToken.balanceOf(address(this));
baseProtocolTokenAmount = baseProtocolToken.balanceOf(address(this));
} else {
// Keep a reference to the number of tokens being used for claims.
uint256 _numberOfTokens = _tokenIds.length;
// Keep a reference to the tier being iterated on.
JB721Tier memory _tier;
// Keep a reference to the cumulative price of the tokens.
uint256 _cumulativePrice;
// Add up the prices of the tokens.
for (uint256 _i; _i < _numberOfTokens;) {
_tier = store.tierOfTokenId(address(this), _tokenIds[_i], false);
_cumulativePrice += _tier.price;
unchecked {
++_i;
}
}
// The amount of $DEFIFA and $BASE_PROTOCOL to send is the same proportion as the amount being redeemed to the total pot before any amount redeemed.
defifaTokenAmount = PRBMath.mulDiv(_defifaTokenAllocation, _cumulativePrice, _pot + amountRedeemed);
baseProtocolTokenAmount =
PRBMath.mulDiv(_baseProtocolTokenAllocation, _cumulativePrice, _pot + amountRedeemed);
}
}
/// @notice Indicates if this contract adheres to the specified interface.
/// @dev See {IERC165-supportsInterface}.
/// @param _interfaceId The ID of the interface to check for adherence to.
function supportsInterface(bytes4 _interfaceId) public view override returns (bool) {
return _interfaceId == type(IDefifaDelegate).interfaceId || super.supportsInterface(_interfaceId);
}
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/// @notice The $DEFIFA token that is expected to be issued from paying fees.
/// @notice The $BASE_PROTOCOL token that is expected to be issued from paying fees.
constructor(IERC20 _defifaToken, IERC20 _baseProtocolToken) {
codeOrigin = address(this);
defifaToken = _defifaToken;
baseProtocolToken = _baseProtocolToken;
}
//*********************************************************************//
// ----------------------- public transactions ----------------------- //
//*********************************************************************//
/// @notice Initialize a clone of this contract.
/// @param _gameId The ID of the project this contract's functionality applies to.
/// @param _directory The directory of terminals and controllers for projects.
/// @param _name The name of the token.
/// @param _symbol The symbol that the token should be represented by.
/// @param _fundingCycleStore A contract storing all funding cycle configurations.
/// @param _baseUri A URI to use as a base for full token URIs.
/// @param _tokenUriResolver A contract responsible for resolving the token URI for each token ID.
/// @param _contractUri A URI where contract metadata can be found.
/// @param _tiers The tiers to set.
/// @param _currency The currency that the tier contribution floors are denoted in.
/// @param _store A contract that stores the NFT's data.
/// @param _gamePhaseReporter The contract that reports the game phase.
/// @param _gamePotReporter The contract that reports the game's pot.
/// @param _defaultAttestationDelegate The address that'll be set as the attestation delegate by default.
/// @param _tierNames The names of each tier.
function initialize(
uint256 _gameId,
IJBDirectory _directory,
string memory _name,
string memory _symbol,
IJBFundingCycleStore _fundingCycleStore,
string memory _baseUri,
IJB721TokenUriResolver _tokenUriResolver,
string memory _contractUri,
JB721TierParams[] memory _tiers,
uint48 _currency,
IJBTiered721DelegateStore _store,
IDefifaGamePhaseReporter _gamePhaseReporter,
IDefifaGamePotReporter _gamePotReporter,
address _defaultAttestationDelegate,
string[] memory _tierNames
) public override {
// Make the original un-initializable.
if (address(this) == codeOrigin) revert();
// Stop re-initialization.
if (address(store) != address(0)) revert();
// Initialize the superclass.
JB721Delegate._initialize({_projectId: _gameId, _directory: _directory, _name: _name, _symbol: _symbol});
// Store stuff.
fundingCycleStore = _fundingCycleStore;
store = _store;
pricingCurrency = _currency;
gamePhaseReporter = _gamePhaseReporter;
gamePotReporter = _gamePotReporter;
defaultAttestationDelegate = _defaultAttestationDelegate;
// Store the base URI if provided.
if (bytes(_baseUri).length != 0) baseURI = _baseUri;
// Set the contract URI if provided.
if (bytes(_contractUri).length != 0) contractURI = _contractUri;
// Set the token URI resolver if provided.
if (_tokenUriResolver != IJB721TokenUriResolver(address(0))) {
_store.recordSetTokenUriResolver(_tokenUriResolver);
}
// Record the provided tiers.
_store.recordAddTiers(_tiers);
// Keep a reference to the number of tier names.
uint256 _numberOfTierNames = _tierNames.length;
// Set the name for each tier.
for (uint256 _i; _i < _numberOfTierNames;) {
// Set the tier name.
_tierNameOf[_i + 1] = _tierNames[_i];
unchecked {
++_i;
}
}
// Transfer ownership to the initializer.
_transferOwnership(msg.sender);
}
/// @notice Mint reserved tokens within the tier for the provided value.
/// @param _tierId The ID of the tier to mint within.
/// @param _count The number of reserved tokens to mint.
function mintReservesFor(uint256 _tierId, uint256 _count) public override {
// Minting reserves must not be paused.
if (
JBTiered721FundingCycleMetadataResolver.mintingReservesPaused(
(JBFundingCycleMetadataResolver.metadata(fundingCycleStore.currentOf(projectId)))
)
) revert RESERVED_TOKEN_MINTING_PAUSED();
// Keep a reference to the reserved token beneficiary.
address _reservedTokenBeneficiary = store.reservedTokenBeneficiaryOf(address(this), _tierId);
// Get a reference to the old delegate.
address _oldDelegate = _tierDelegation[_reservedTokenBeneficiary][_tierId];
// Set the delegate as the beneficiary if the beneficiary hasn't already set a delegate.
if (_oldDelegate == address(0)) {
_delegateTier(
_reservedTokenBeneficiary,
defaultAttestationDelegate != address(0) ? defaultAttestationDelegate : _reservedTokenBeneficiary,
_tierId
);
}
// Record the minted reserves for the tier.
uint256[] memory _tokenIds = store.recordMintReservesFor(_tierId, _count);
// Keep a reference to the token ID being iterated on.
uint256 _tokenId;
for (uint256 _i; _i < _count;) {
// Set the token ID.
_tokenId = _tokenIds[_i];
// Mint the token.
_mint(_reservedTokenBeneficiary, _tokenId);
emit MintReservedToken(_tokenId, _tierId, _reservedTokenBeneficiary, msg.sender);
unchecked {
++_i;
}
}
// Transfer the attestation units to the delegate.
_transferTierAttestationUnits(
address(0),
_reservedTokenBeneficiary,
_tierId,
store.tierOf(address(this), _tierId, false).votingUnits * _tokenIds.length
);
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/// @notice Stores the redemption weights that should be used in the end game phase.
/// @dev Only this contract's owner can set tier redemption weights.
/// @param _tierWeights The tier weights to set.
function setTierRedemptionWeightsTo(DefifaTierRedemptionWeight[] memory _tierWeights) external override onlyOwner {
// Get a reference to the game phase.
DefifaGamePhase _gamePhase = gamePhaseReporter.currentGamePhaseOf(projectId);
// Make sure the game has ended.
if (_gamePhase != DefifaGamePhase.SCORING) {
revert GAME_ISNT_SCORING_YET();
}
// Make sure the redemption weights haven't already been set.
if (redemptionWeightIsSet) revert REDEMPTION_WEIGHTS_ALREADY_SET();
// Make sure the game is not in no contest.
if (_gamePhase == DefifaGamePhase.NO_CONTEST || _gamePhase == DefifaGamePhase.NO_CONTEST_INEVITABLE) {
revert NO_CONTEST();
}
// Keep a reference to the max tier ID.
uint256 _maxTierId = store.maxTierIdOf(address(this));
// Keep a reference to the cumulative amounts.
uint256 _cumulativeRedemptionWeight;
// Keep a reference to the number of tier weights.
uint256 _numberOfTierWeights = _tierWeights.length;
// Keep a reference to the tier being iterated on.
JB721Tier memory _tier;
for (uint256 _i; _i < _numberOfTierWeights;) {
// Get the tier.
_tier = store.tierOf(address(this), _tierWeights[_i].id, false);
// Can't set a redemption weight for tiers not in category 0.
if (_tier.category != 0) revert INVALID_TIER_ID();
// Attempting to set the redemption weight for a tier that does not exist (yet) reverts.
if (_tier.id > _maxTierId) revert INVALID_TIER_ID();
// Save the tier weight. Tier's are 1 indexed and should be stored 0 indexed.
_tierRedemptionWeights[_tier.id - 1] = _tierWeights[_i].redemptionWeight;
// Increment the cumulative amount.
_cumulativeRedemptionWeight += _tierWeights[_i].redemptionWeight;
unchecked {
++_i;
}
}
// Make sure the cumulative amount is contained within the total redemption weight.
if (_cumulativeRedemptionWeight > TOTAL_REDEMPTION_WEIGHT) revert INVALID_REDEMPTION_WEIGHTS();
// Mark the redemption weight as set.
redemptionWeightIsSet = true;
emit TierRedemptionWeightsSet(_tierWeights, msg.sender);
}
/// @notice Part of IJBRedeemDelegate, this function gets called when the token holder redeems. It will burn the specified NFTs to reclaim from the treasury to the _data.beneficiary.
/// @dev This function will revert if the contract calling is not one of the project's terminals.
/// @param _data The Juicebox standard project redemption data.
function didRedeem(JBDidRedeemData calldata _data) external payable virtual override {
// Make sure the caller is a terminal of the project, and the call is being made on behalf of an interaction with the correct project.
if (
msg.value != 0 || !directory.isTerminalOf(projectId, IJBPaymentTerminal(msg.sender))
|| _data.projectId != projectId
) revert INVALID_REDEMPTION_EVENT();
// If there's nothing being claimed, revert to prevent burning for nothing.
if (_data.reclaimedAmount.value == 0) revert NOTHING_TO_CLAIM();
// Check the 4 bytes interfaceId and handle the case where the metadata was not intended for this contract
// Skip 32 bytes reserved for generic extension parameters.
if (_data.metadata.length < 36 || bytes4(_data.metadata[32:36]) != type(IDefifaDelegate).interfaceId) {
revert INVALID_REDEMPTION_METADATA();
}
// Decode the metadata.
(,, uint256[] memory _decodedTokenIds) = abi.decode(_data.metadata, (bytes32, bytes4, uint256[]));
// Get a reference to the number of token IDs being checked.
uint256 _numberOfTokenIds = _decodedTokenIds.length;
// Keep a reference to the token ID being iterated on.
uint256 _tokenId;
// Keep track of whether the redemption is happening during the complete phase.
bool _isComplete = gamePhaseReporter.currentGamePhaseOf(projectId) == DefifaGamePhase.COMPLETE;
// Iterate through all tokens, burning them if the owner is correct.
for (uint256 _i; _i < _numberOfTokenIds;) {
// Set the token's ID.
_tokenId = _decodedTokenIds[_i];
// Make sure the token's owner is correct.
if (_owners[_tokenId] != _data.holder) revert UNAUTHORIZED();
// Burn the token.
_burn(_tokenId);
unchecked {
if (_isComplete) ++tokensRedeemedFrom[store.tierIdOfToken(_tokenId)];
++_i;
}
}
// Call the hook.
_didBurn(_decodedTokenIds);
// Increment the amount redeemed if this is the complete phase.
if (_isComplete) {
amountRedeemed += _data.reclaimedAmount.value;
// Claim any $DEFIFA and $BASE_PROTOCOL tokens available.
_claimTokensFor(_data.holder, _decodedTokenIds);
}
}
/// @notice Mint reserved tokens within the tier for the provided value.
/// @param _mintReservesForTiersData Contains information about how many reserved tokens to mint for each tier.
function mintReservesFor(JBTiered721MintReservesForTiersData[] calldata _mintReservesForTiersData)
external
override
{
// Keep a reference to the number of tiers there are to mint reserves for.
uint256 _numberOfTiers = _mintReservesForTiersData.length;
for (uint256 _i; _i < _numberOfTiers;) {
// Get a reference to the data being iterated on.
JBTiered721MintReservesForTiersData memory _data = _mintReservesForTiersData[_i];
// Mint for the tier.
mintReservesFor(_data.tierId, _data.count);
unchecked {
++_i;
}
}
}
/// @notice Delegate attestations.
/// @param _setTierDelegatesData An array of tiers to set delegates for.
function setTierDelegatesTo(JBTiered721SetTierDelegatesData[] memory _setTierDelegatesData)
external
virtual
override
{
// Make sure the current game phase is the minting phase.
if (gamePhaseReporter.currentGamePhaseOf(projectId) != DefifaGamePhase.MINT) {
revert DELEGATE_CHANGES_UNAVAILABLE_IN_THIS_PHASE();
}
// Keep a reference to the number of tier delegates.
uint256 _numberOfTierDelegates = _setTierDelegatesData.length;
// Keep a reference to the data being iterated on.
JBTiered721SetTierDelegatesData memory _data;
for (uint256 _i; _i < _numberOfTierDelegates;) {
// Reference the data being iterated on.
_data = _setTierDelegatesData[_i];
// Make sure a delegate is specified.
if (_data.delegatee == address(0)) revert DELEGATE_ADDRESS_ZERO();
_delegateTier(msg.sender, _data.delegatee, _data.tierId);
unchecked {
++_i;
}
}
}
/// @notice Delegate attestations.
/// @param _delegatee The account to delegate tier attestation units to.
/// @param _tierId The ID of the tier to delegate attestation units for.
function setTierDelegateTo(address _delegatee, uint256 _tierId) public virtual override {
// Make sure the current game phase is the minting phase.
if (gamePhaseReporter.currentGamePhaseOf(projectId) != DefifaGamePhase.MINT) {
revert DELEGATE_CHANGES_UNAVAILABLE_IN_THIS_PHASE();
}
_delegateTier(msg.sender, _delegatee, _tierId);
}
//*********************************************************************//
// ------------------------ internal functions ----------------------- //
//*********************************************************************//
/// @notice Process an incoming payment.
/// @param _data The Juicebox standard project payment data.
function _processPayment(JBDidPayData calldata _data) internal override {
// Make sure the game is being played in the correct currency.
if (_data.amount.currency != pricingCurrency) revert WRONG_CURRENCY();
// Keep a reference to the address that should be given attestations from this mint.
address _attestationDelegate;
// Skip the first 32 bytes which are used by the JB protocol to pass the paying project's ID when paying from a JBSplit.
// Check the 4 bytes interfaceId to verify the metadata is intended for this contract.
if (_data.metadata.length > 68 && bytes4(_data.metadata[64:68]) == type(IDefifaDelegate).interfaceId) {
// Keep a reference to the the specific tier IDs to mint.
uint16[] memory _tierIdsToMint;
// Decode the metadata.
(,,, _attestationDelegate, _tierIdsToMint) =
abi.decode(_data.metadata, (bytes32, bytes32, bytes4, address, uint16[]));
// Set the payer as the attestation delegate by default.
if (_attestationDelegate == address(0)) {
_attestationDelegate =
defaultAttestationDelegate != address(0) ? defaultAttestationDelegate : _data.payer;
}
// Make sure something is being minted.
if (_tierIdsToMint.length == 0) revert NOTHING_TO_MINT();
// Keep a reference to the current tier ID.
uint256 _currentTierId;
// Keep a reference to the number of attestations units currently accumulated for the given tier.
uint256 _attestationUnitsForCurrentTier;
// The price of the tier being iterated on.
uint256 _attestationUnits;
// Keep a reference to the number of tiers.
uint256 _numberOfTiers = _tierIdsToMint.length;
// Transfer attestation units for each tier.
for (uint256 _i; _i < _numberOfTiers;) {
// Keep track of the current tier being iterated on and its price.
if (_currentTierId != _tierIdsToMint[_i]) {
// Make sure the tier IDs are passed in order.
if (_tierIdsToMint[_i] < _currentTierId) revert BAD_TIER_ORDER();
_currentTierId = _tierIdsToMint[_i];
_attestationUnits = store.tierOf(address(this), _currentTierId, false).votingUnits;
}
// Get a reference to the old delegate.
address _oldDelegate = _tierDelegation[_data.payer][_currentTierId];
// If there's either a new delegate or old delegate, increase the delegate weight.
if (_attestationDelegate != address(0) || _oldDelegate != address(0)) {
// Increment the total attestation units for the tier based on price.
if (_i < _numberOfTiers - 1 && _tierIdsToMint[_i + 1] == _currentTierId) {
_attestationUnitsForCurrentTier += _attestationUnits;
// Set the tier's total attestation units.
} else {
// Switch delegates if needed.
if (_attestationDelegate != address(0) && _attestationDelegate != _oldDelegate) {
_delegateTier(_data.payer, _attestationDelegate, _currentTierId);
}
// Transfer the new attestation units.
_transferTierAttestationUnits(
address(0), _data.payer, _currentTierId, _attestationUnitsForCurrentTier + _attestationUnits
);
// Reset the counter
_attestationUnitsForCurrentTier = 0;
}
}
unchecked {
++_i;
}
}
// Mint tiers if they were specified.
uint256 _leftoverAmount = _mintAll(_data.amount.value, _tierIdsToMint, _data.beneficiary);
// Make sure the buyer isn't overspending.
if (_leftoverAmount != 0) revert OVERSPENDING();
}
}
/// @notice Gets the amount of attestation units an address has for a particular tier.
/// @param _account The account to get attestation units for.
/// @param _tierId The ID of the tier to get attestation units for.
/// @return The attestation units.
function _getTierAttestationUnits(address _account, uint256 _tierId) internal view virtual returns (uint256) {
return store.tierVotingUnitsOf(address(this), _account, _tierId);
}
/// @notice Delegate all attestation units for the specified tier.
/// @param _account The account delegating tier attestation units.
/// @param _delegatee The account to delegate tier attestation units to.
/// @param _tierId The ID of the tier for which attestation units are being transferred.
function _delegateTier(address _account, address _delegatee, uint256 _tierId) internal virtual {
// Get the current delegatee
address _oldDelegate = _tierDelegation[_account][_tierId];
// Store the new delegatee
_tierDelegation[_account][_tierId] = _delegatee;
emit DelegateChanged(_account, _oldDelegate, _delegatee);
// Move the attestations.
_moveTierDelegateAttestations(_oldDelegate, _delegatee, _tierId, _getTierAttestationUnits(_account, _tierId));
}
/// @notice Transfers, mints, or burns tier attestation units. To register a mint, `_from` should be zero. To register a burn, `_to` should be zero. Total supply of attestation units will be adjusted with mints and burns.
/// @param _from The account to transfer tier attestation units from.
/// @param _to The account to transfer tier attestation units to.
/// @param _tierId The ID of the tier for which attestation units are being transferred.
/// @param _amount The amount of attestation units to delegate.
function _transferTierAttestationUnits(address _from, address _to, uint256 _tierId, uint256 _amount)
internal
virtual
{
// If minting, add to the total tier checkpoints.
if (_from == address(0)) _totalTierCheckpoints[_tierId].push(_add, _amount);
// If burning, subtract from the total tier checkpoints.
if (_to == address(0)) _totalTierCheckpoints[_tierId].push(_subtract, _amount);
// Move delegated attestations.
_moveTierDelegateAttestations(_tierDelegation[_from][_tierId], _tierDelegation[_to][_tierId], _tierId, _amount);
}
/// @notice Moves delegated tier attestations from one delegate to another.
/// @param _from The account to transfer tier attestation units from.
/// @param _to The account to transfer tier attestation units to.
/// @param _tierId The ID of the tier for which attestation units are being transferred.
/// @param _amount The amount of attestation units to delegate.
function _moveTierDelegateAttestations(address _from, address _to, uint256 _tierId, uint256 _amount) internal {
// Nothing to do if moving to the same account, or no amount is being moved.
if (_from == _to || _amount == 0) return;
// If not moving from the zero address, update the checkpoints to subtract the amount.
if (_from != address(0)) {
(uint256 _oldValue, uint256 _newValue) = _delegateTierCheckpoints[_from][_tierId].push(_subtract, _amount);
emit TierDelegateAttestationsChanged(_from, _tierId, _oldValue, _newValue, msg.sender);
}
// If not moving to the zero address, update the checkpoints to add the amount.
if (_to != address(0)) {
(uint256 _oldValue, uint256 _newValue) = _delegateTierCheckpoints[_to][_tierId].push(_add, _amount);
emit TierDelegateAttestationsChanged(_to, _tierId, _oldValue, _newValue, msg.sender);
}
}
/// @notice A function that will run when tokens are burned via redemption.
/// @param _tokenIds The IDs of the tokens that were burned.
function _didBurn(uint256[] memory _tokenIds) internal virtual override {
// Add to burned counter.
store.recordBurn(_tokenIds);
}
/// @notice Mints a token in all provided tiers.
/// @param _amount The amount to base the mints on. All mints' price floors must fit in this amount.
/// @param _mintTierIds An array of tier IDs that are intended to be minted.
/// @param _beneficiary The address to mint for.
/// @return leftoverAmount The amount leftover after the mint.
function _mintAll(uint256 _amount, uint16[] memory _mintTierIds, address _beneficiary)
internal
returns (uint256 leftoverAmount)
{
// Keep a reference to the token ID.
uint256[] memory _tokenIds;
// Record the mint. The returned token IDs correspond to the tiers passed in.
(_tokenIds, leftoverAmount) = store.recordMint(
_amount,
_mintTierIds,
false // Not a manual mint
);
// Get a reference to the number of mints.
uint256 _mintsLength = _tokenIds.length;
// Keep a reference to the token ID being iterated on.
uint256 _tokenId;
// Loop through each token ID and mint.
for (uint256 _i; _i < _mintsLength;) {
// Get a reference to the tier being iterated on.
_tokenId = _tokenIds[_i];
// Mint the tokens.
_mint(_beneficiary, _tokenId);
emit Mint(_tokenId, _mintTierIds[_i], _beneficiary, _amount, msg.sender);
unchecked {
++_i;
}
}
}
/// @notice Claim $DEFIFA and $BASE_PROTOCOL tokens to an account for a certain redeemed amount.
/// @param _beneficiary The beneficiary of the $DEFIFA tokens.
/// @param _tokenIds The IDs of the tokens being redeemed that are justifying a $DEFIFA claim.
function _claimTokensFor(address _beneficiary, uint256[] memory _tokenIds) internal {