-
Notifications
You must be signed in to change notification settings - Fork 8
/
JBTiered721DelegateStore.sol
1333 lines (1062 loc) · 42.9 KB
/
JBTiered721DelegateStore.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 '@jbx-protocol/juice-contracts-v3/contracts/libraries/JBConstants.sol';
import './interfaces/IJBTiered721DelegateStore.sol';
import './libraries/JBBitmap.sol';
import './structs/JBBitmapWord.sol';
import './structs/JBStored721Tier.sol';
/**
@title
JBTiered721DelegateStore
@notice
The contract that stores and manages the NFT's data.
@dev
Adheres to -
IJBTiered721DelegateStore: General interface for the methods in this contract that interact with the blockchain's state according to the protocol's rules.
*/
contract JBTiered721DelegateStore is IJBTiered721DelegateStore {
using JBBitmap for mapping(uint256=>uint256);
using JBBitmap for JBBitmapWord;
//*********************************************************************//
// --------------------------- custom errors ------------------------- //
//*********************************************************************//
error CANT_MINT_MANUALLY();
error INSUFFICIENT_AMOUNT();
error INSUFFICIENT_RESERVES();
error INVALID_TIER();
error NO_QUANTITY();
error OUT();
error RESERVED_RATE_NOT_ALLOWED();
error MANUAL_MINTING_NOT_ALLOWED();
error PRICING_RESOLVER_CHANGES_LOCKED();
error TIER_LOCKED();
error TIER_REMOVED();
error VOTING_UNITS_NOT_ALLOWED();
error INVALID_PRICE_SORT_ORDER();
//*********************************************************************//
// --------------------- internal stored properties ------------------ //
//*********************************************************************//
/**
@notice
The index that should come after the given index when sorting by contribution floor.
@dev
If empty, assume the next index should come after.
_nft The NFT contract to get tier order index from.
_index The index to get a tier after relative to.
*/
mapping(address => mapping(uint256 => uint256)) internal _tierIdAfter;
/**
@notice
An optional beneficiary for the reserved token of a given tier.
_nft The NFT contract to which the reserved token beneficiary belongs.
_tierId the ID of the tier.
*/
mapping(address => mapping(uint256 => address)) internal _reservedTokenBeneficiaryOf;
/**
@notice
The stored reward tier.
_nft The NFT contract to which the tiers belong.
_tierId The incremental ID of the tier, starting with 1.
*/
mapping(address => mapping(uint256 => JBStored721Tier)) internal _storedTierOf;
/**
@notice
Flags that influence the behavior of each NFT.
_nft The NFT for which the flags apply.
*/
mapping(address => JBTiered721Flags) internal _flagsOf;
/**
@notice
For each tier ID, a flag indicating if the tier has been removed.
_nft The NFT contract to which the tier belong.
_depth The bitmap row
_word The row content
*/
mapping(address => mapping(uint256 => uint256)) internal _isTierRemoved;
/**
@notice
For each NFT, the tier ID that comes last when sorting.
@dev
If not set, it is assumed the `maxTierIdOf` is the last sorted.
_nft The NFT contract to which the tier belongs.
*/
mapping(address => uint256) internal _trackedLastSortTierIdOf;
//*********************************************************************//
// --------------------- public stored properties -------------------- //
//*********************************************************************//
/**
@notice
The biggest tier ID used.
@dev
This may not include the last tier ID if it has been removed.
_nft The NFT contract to get the number of tiers.
*/
mapping(address => uint256) public override maxTierIdOf;
/**
@notice
Each account's balance within a specific tier.
_nft The NFT contract to which the tier balances belong.
_owner The address to get a balance for.
_tierId The ID of the tier to get a balance within.
*/
mapping(address => mapping(address => mapping(uint256 => uint256))) public override tierBalanceOf;
/**
@notice
The number of reserved tokens that have been minted for each tier.
_nft The NFT contract to which the reserve data belong.
_tierId The ID of the tier to get a minted reserved token count for.
*/
mapping(address => mapping(uint256 => uint256)) public override numberOfReservesMintedFor;
/**
@notice
The number of tokens that have been burned for each tier.
_nft The NFT contract to which the burned data belong.
_tierId The ID of the tier to get a burned token count for.
*/
mapping(address => mapping(uint256 => uint256)) public override numberOfBurnedFor;
/**
@notice
The beneficiary of reserved tokens when the tier doesn't specify a beneficiary.
_nft The NFT contract to which the reserved token beneficiary applies.
*/
mapping(address => address) public override defaultReservedTokenBeneficiaryOf;
/**
@notice
The first owner of each token ID, stored on first transfer out.
_nft The NFT contract to which the token belongs.
_tokenId The ID of the token to get the stored first owner of.
*/
mapping(address => mapping(uint256 => address)) public override firstOwnerOf;
/**
@notice
The common base for the tokenUri's
_nft The NFT for which the base URI applies.
*/
mapping(address => string) public override baseUriOf;
/**
@notice
Custom token URI resolver, superceeds base URI.
_nft The NFT for which the token URI resolver applies.
*/
mapping(address => IJBTokenUriResolver) public override tokenUriResolverOf;
/**
@notice
Contract metadata uri.
_nft The NFT for which the contract URI resolver applies.
*/
mapping(address => string) public override contractUriOf;
/**
@notice
When using this contract to manage token uri's, those are stored as 32bytes, based on IPFS hashes stripped down.
_nft The NFT contract to which the encoded upfs uri belongs.
_tierId the ID of the tier
*/
mapping(address => mapping(uint256 => bytes32)) public override encodedIPFSUriOf;
//*********************************************************************//
// ------------------------- external views -------------------------- //
//*********************************************************************//
/**
@notice
Gets an array of all the active tiers.
@param _nft The NFT contract to get tiers for.
@param _startingId The start index of the array of tiers sorted by contribution floor. Send 0 to start at the beginning.
@param _size The number of tiers to include.
@return _tiers All the tiers.
*/
function tiers(
address _nft,
uint256 _startingId,
uint256 _size
) external view override returns (JB721Tier[] memory _tiers) {
// Keep a reference to the last tier ID.
uint256 _lastTierId = _lastSortIndexOf(_nft);
// Initialize an array with the appropriate length.
_tiers = new JB721Tier[](_size);
// Count the number of included tiers.
uint256 _numberOfIncludedTiers;
// Get a reference to the index being iterated on, starting with the starting index.
uint256 _currentSortIndex = _startingId != 0 ? _startingId : _firstSortIndexOf(_nft);
// Keep a referecen to the tier being iterated on.
JBStored721Tier memory _storedTier;
// Initialise a BitmapWord for isRemoved
JBBitmapWord memory _bitmapWord = _isTierRemoved[_nft].readId(_currentSortIndex);
// Make the sorted array.
while (_currentSortIndex != 0 && _numberOfIncludedTiers < _size) {
// Is the current index outside the currently stored word for isRemoved?
if (_bitmapWord.refreshBitmapNeeded(_currentSortIndex))
_bitmapWord = _isTierRemoved[_nft].readId(_currentSortIndex);
if (!_bitmapWord.isTierIdRemoved(_currentSortIndex)) {
_storedTier = _storedTierOf[_nft][_currentSortIndex];
// Add the tier to the array being returned.
_tiers[_numberOfIncludedTiers++] = JB721Tier({
id: _currentSortIndex,
contributionFloor: _storedTier.contributionFloor,
lockedUntil: _storedTier.lockedUntil,
remainingQuantity: _storedTier.remainingQuantity,
initialQuantity: _storedTier.initialQuantity,
votingUnits: _storedTier.votingUnits,
reservedRate: _storedTier.reservedRate,
reservedTokenBeneficiary: reservedTokenBeneficiaryOf(_nft, _currentSortIndex),
encodedIPFSUri: encodedIPFSUriOf[_nft][_currentSortIndex],
allowManualMint: _storedTier.allowManualMint
});
}
// Set the next sort index.
_currentSortIndex = _nextSortIndex(_nft, _currentSortIndex, _lastTierId);
}
// Resize the array if there are removed tiers
if (_numberOfIncludedTiers != _size)
assembly ("memory-safe"){
mstore(_tiers, _numberOfIncludedTiers)
}
}
/**
@notice
Return the tier for the specified ID.
@param _nft The NFT to get a tier within.
@param _id The ID of the tier to get.
@return The tier.
*/
function tier(address _nft, uint256 _id) external view override returns (JB721Tier memory) {
// Get the stored tier.
JBStored721Tier memory _storedTier = _storedTierOf[_nft][_id];
return
JB721Tier({
id: _id,
contributionFloor: _storedTier.contributionFloor,
lockedUntil: _storedTier.lockedUntil,
remainingQuantity: _storedTier.remainingQuantity,
initialQuantity: _storedTier.initialQuantity,
votingUnits: _storedTier.votingUnits,
reservedRate: _storedTier.reservedRate,
reservedTokenBeneficiary: reservedTokenBeneficiaryOf(_nft, _id),
encodedIPFSUri: encodedIPFSUriOf[_nft][_id],
allowManualMint: _storedTier.allowManualMint
});
}
/**
@notice
Return the tier for the specified token ID.
@param _nft The NFT to get a tier within.
@param _tokenId The ID of token to return the tier of.
@return The tier.
*/
function tierOfTokenId(address _nft, uint256 _tokenId)
external
view
override
returns (JB721Tier memory)
{
// Get a reference to the tier's ID.
uint256 _tierId = tierIdOfToken(_tokenId);
// Get the stored tier.
JBStored721Tier memory _storedTier = _storedTierOf[_nft][_tierId];
return
JB721Tier({
id: _tierId,
contributionFloor: _storedTier.contributionFloor,
lockedUntil: _storedTier.lockedUntil,
remainingQuantity: _storedTier.remainingQuantity,
initialQuantity: _storedTier.initialQuantity,
votingUnits: _storedTier.votingUnits,
reservedRate: _storedTier.reservedRate,
reservedTokenBeneficiary: reservedTokenBeneficiaryOf(_nft, _tierId),
encodedIPFSUri: encodedIPFSUriOf[_nft][_tierId],
allowManualMint: _storedTier.allowManualMint
});
}
/**
@notice
The total supply of issued NFTs from all tiers.
@param _nft The NFT to get a total supply of.
@return supply The total number of NFTs between all tiers.
*/
function totalSupply(address _nft) external view override returns (uint256 supply) {
// Keep a reference to the tier being iterated on.
JBStored721Tier storage _storedTier;
// Keep a reference to the greatest tier ID.
uint256 _maxTierId = maxTierIdOf[_nft];
for (uint256 _i = _maxTierId; _i != 0; ) {
// Set the tier being iterated on.
_storedTier = _storedTierOf[_nft][_i];
// Increment the total supply with the amount used already.
supply += _storedTier.initialQuantity - _storedTier.remainingQuantity;
unchecked {
--_i;
}
}
}
/**
@notice
The number of reserved tokens that can currently be minted within the tier.
@param _nft The NFT to get a number of reserved tokens outstanding.
@param _tierId The ID of the tier to get a number of reserved tokens outstanding.
@return The outstanding number of reserved tokens within the tier.
*/
function numberOfReservedTokensOutstandingFor(address _nft, uint256 _tierId)
external
view
override
returns (uint256)
{
return _numberOfReservedTokensOutstandingFor(_nft, _tierId, _storedTierOf[_nft][_tierId]);
}
/**
@notice
The voting units for an account from its NFTs across all tiers. NFTs have a tier-specific preset number of voting units.
@param _nft The NFT to get voting units within.
@param _account The account to get voting units for.
@return units The voting units for the account.
*/
function votingUnitsOf(address _nft, address _account)
external
view
virtual
override
returns (uint256 units)
{
// Keep a reference to the greatest tier ID.
uint256 _maxTierId = maxTierIdOf[_nft];
// Keep a reference to the balance being iterated on.
uint256 _balance;
// Loop through all tiers.
for (uint256 _i = _maxTierId; _i != 0; ) {
// Get a reference to the account's balance in this tier.
_balance = tierBalanceOf[_nft][_account][_i];
if (_balance != 0)
// Add the tier's voting units.
units += _balance * _storedTierOf[_nft][_i].votingUnits;
unchecked {
--_i;
}
}
}
/**
@notice
The voting units for an account from its NFTs across all tiers. NFTs have a tier-specific preset number of voting units.
@param _nft The NFT to get voting units within.
@param _account The account to get voting units for.
@param _tierId The ID of the tier to get voting units for.
@return The voting units for the account.
*/
function tierVotingUnitsOf(
address _nft,
address _account,
uint256 _tierId
) external view virtual override returns (uint256) {
// Get a reference to the account's balance in this tier.
uint256 _balance = tierBalanceOf[_nft][_account][_tierId];
if (_balance == 0) return 0;
// Add the tier's voting units.
return _balance * _storedTierOf[_nft][_tierId].votingUnits;
}
/**
@notice
Resolves the encoded tier IPFS URI of the tier for the given token.
@param _nft The NFT contract to which the encoded IPFS URI belongs.
@param _tokenId the ID of the token.
@return The encoded IPFS URI.
*/
function encodedTierIPFSUriOf(address _nft, uint256 _tokenId)
external
view
override
returns (bytes32)
{
return encodedIPFSUriOf[_nft][tierIdOfToken(_tokenId)];
}
/**
@notice
Flags that influence the behavior of each NFT.
@param _nft The NFT for which the flags apply.
@return The flags.
*/
function flagsOf(address _nft) external view override returns (JBTiered721Flags memory) {
return _flagsOf[_nft];
}
/**
@notice
Tier removed from the current tiering
@param _nft The NFT for which the removed tier is queried
@param _tierId The tier ID
@return True if the tier has been removed
*/
function isTierRemoved(address _nft, uint256 _tierId) external view override returns(bool) {
JBBitmapWord memory _bitmapWord = _isTierRemoved[_nft].readId(_tierId);
return _bitmapWord.isTierIdRemoved(_tierId);
}
//*********************************************************************//
// -------------------------- public views --------------------------- //
//*********************************************************************//
/**
@notice
The total number of tokens owned by the given owner.
@param _nft The NFT to get a balance from.
@param _owner The address to check the balance of.
@return balance The number of tokens owners by the owner accross all tiers.
*/
function balanceOf(address _nft, address _owner) public view override returns (uint256 balance) {
// Keep a reference to the greatest tier ID.
uint256 _maxTierId = maxTierIdOf[_nft];
// Loop through all tiers.
for (uint256 _i = _maxTierId; _i != 0; ) {
// Get a reference to the account's balance in this tier.
balance += tierBalanceOf[_nft][_owner][_i];
unchecked {
--_i;
}
}
}
/**
@notice
The cumulative weight the given token IDs have in redemptions compared to the `totalRedemptionWeight`.
@param _nft The NFT for which the redemption weight is being calculated.
@param _tokenIds The IDs of the tokens to get the cumulative redemption weight of.
@return weight The weight.
*/
function redemptionWeightOf(address _nft, uint256[] calldata _tokenIds)
public
view
override
returns (uint256 weight)
{
// Get a reference to the total number of tokens.
uint256 _numberOfTokenIds = _tokenIds.length;
// Add each token's tier's contribution floor to the weight.
for (uint256 _i; _i < _numberOfTokenIds; ) {
weight += _storedTierOf[_nft][tierIdOfToken(_tokenIds[_i])].contributionFloor;
unchecked {
++_i;
}
}
}
/**
@notice
The cumulative weight that all token IDs have in redemptions.
@param _nft The NFT for which the redemption weight is being calculated.
@return weight The total weight.
*/
function totalRedemptionWeight(address _nft) public view override returns (uint256 weight) {
// Keep a reference to the greatest tier ID.
uint256 _maxTierId = maxTierIdOf[_nft];
// Keep a reference to the tier being iterated on.
JBStored721Tier memory _storedTier;
// Add each token's tier's contribution floor to the weight.
for (uint256 _i; _i < _maxTierId; ) {
// Keep a reference to the stored tier.
_storedTier = _storedTierOf[_nft][_i + 1];
// Add the tier's contribution floor multiplied by the quantity minted.
weight +=
(_storedTier.contributionFloor *
(_storedTier.initialQuantity - _storedTier.remainingQuantity)) +
_numberOfReservedTokensOutstandingFor(_nft, _i, _storedTier);
unchecked {
++_i;
}
}
}
/**
@notice
The tier number of the provided token ID.
@dev
Tier's are 1 indexed from the `tiers` array, meaning the 0th element of the array is tier 1.
@param _tokenId The ID of the token to get the tier number of.
@return The tier number of the specified token ID.
*/
function tierIdOfToken(uint256 _tokenId) public pure override returns (uint256) {
// The tier ID is in the first 16 bits.
return uint256(uint16(_tokenId));
}
/**
@notice
The reserved token beneficiary for each tier.
@param _nft The NFT to get the reserved token beneficiary within.
@param _tierId The ID of the tier to get a reserved token beneficiary of.
@return The reserved token benficiary.
*/
function reservedTokenBeneficiaryOf(address _nft, uint256 _tierId)
public
view
override
returns (address)
{
// Get the stored reserved token beneficiary.
address _storedReservedTokenBeneficiaryOfTier = _reservedTokenBeneficiaryOf[_nft][_tierId];
// If the tier has a beneficiary return it.
if (_storedReservedTokenBeneficiaryOfTier != address(0))
return _storedReservedTokenBeneficiaryOfTier;
// Return the default.
return defaultReservedTokenBeneficiaryOf[_nft];
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/**
@notice
Adds tiers.
@param _tiersToAdd The tiers to add.
@return tierIds The IDs of the tiers added.
*/
function recordAddTiers(JB721TierParams[] memory _tiersToAdd)
external
override
returns (uint256[] memory tierIds)
{
// Get a reference to the number of new tiers.
uint256 _numberOfNewTiers = _tiersToAdd.length;
// Keep a reference to the greatest tier ID.
uint256 _currentMaxTierIdOf = maxTierIdOf[msg.sender];
// Keep a reference to the current last sorted tier ID.
uint256 _currentLastSortIndex = _lastSortIndexOf(msg.sender);
// Initialize an array with the appropriate length.
tierIds = new uint256[](_numberOfNewTiers);
// Keep a reference to the starting sort ID for sorting new tiers if needed.
// There's no need for sorting if there are currently no tiers.
// If there's no sort index, start with the first index.
uint256 _startSortIndex = _currentMaxTierIdOf == 0 ? 0 : _firstSortIndexOf(msg.sender);
// Keep track of the previous index.
uint256 _previous;
// Keep a reference to the tier being iterated on.
JB721TierParams memory _tierToAdd;
// Keep a reference to the flags.
JBTiered721Flags memory _flags = _flagsOf[msg.sender];
for (uint256 _i; _i < _numberOfNewTiers; ) {
// Set the tier being iterated on.
_tierToAdd = _tiersToAdd[_i];
// Make sure the tier's contribution floor is greater than or equal to the previous contribution floor.
if (_i != 0 && _tierToAdd.contributionFloor < _tiersToAdd[_i - 1].contributionFloor)
revert INVALID_PRICE_SORT_ORDER();
// Make sure there are no voting units set if they're not allowed.
if (_flags.lockVotingUnitChanges && _tierToAdd.votingUnits != 0)
revert VOTING_UNITS_NOT_ALLOWED();
// Make sure a reserved rate isn't set if changes should be locked or if manual minting is allowed.
if (
(_flags.lockReservedTokenChanges || _tierToAdd.allowManualMint) &&
_tierToAdd.reservedRate != 0
) revert RESERVED_RATE_NOT_ALLOWED();
// Make sure manual minting is not set if not allowed.
if (_flags.lockManualMintingChanges && _tierToAdd.allowManualMint)
revert MANUAL_MINTING_NOT_ALLOWED();
// Make sure there is some quantity.
if (_tierToAdd.initialQuantity == 0) revert NO_QUANTITY();
// Get a reference to the tier ID.
uint256 _tierId = _currentMaxTierIdOf + _i + 1;
// Add the tier with the iterative ID.
_storedTierOf[msg.sender][_tierId] = JBStored721Tier({
contributionFloor: uint80(_tierToAdd.contributionFloor),
lockedUntil: uint48(_tierToAdd.lockedUntil),
remainingQuantity: uint40(_tierToAdd.initialQuantity),
initialQuantity: uint40(_tierToAdd.initialQuantity),
votingUnits: uint16(_tierToAdd.votingUnits),
reservedRate: uint16(_tierToAdd.reservedRate),
allowManualMint: _tierToAdd.allowManualMint
});
// Set the reserved token beneficiary if needed.
if (
_tierToAdd.reservedTokenBeneficiary != address(0) &&
_tierToAdd.reservedTokenBeneficiary != defaultReservedTokenBeneficiaryOf[msg.sender]
) {
if (_tierToAdd.shouldUseBeneficiaryAsDefault)
defaultReservedTokenBeneficiaryOf[msg.sender] = _tierToAdd.reservedTokenBeneficiary;
else _reservedTokenBeneficiaryOf[msg.sender][_tierId] = _tierToAdd.reservedTokenBeneficiary;
}
// Set the encodedIPFSUri if needed.
if (_tierToAdd.encodedIPFSUri != bytes32(0))
encodedIPFSUriOf[msg.sender][_tierId] = _tierToAdd.encodedIPFSUri;
if (_startSortIndex != 0) {
// Keep track of the sort index.
uint256 _currentSortIndex = _startSortIndex;
// Initialise a BitmapWord for isRemoved
JBBitmapWord memory _bitmapWord = _isTierRemoved[msg.sender].readId(_currentSortIndex);
// Keep a reference to the idex to iterate on next.
uint256 _next;
while (_currentSortIndex != 0) {
// Is the current index outside the currently stored word?
if (_bitmapWord.refreshBitmapNeeded(_currentSortIndex))
_bitmapWord = _isTierRemoved[msg.sender].readId(_currentSortIndex);
// Set the next index.
_next = _nextSortIndex(msg.sender, _currentSortIndex, _currentLastSortIndex);
// If the contribution floor is less than the tier being iterated on, store the order.
if (
_tierToAdd.contributionFloor <
_storedTierOf[msg.sender][_currentSortIndex].contributionFloor
) {
// If the index being iterated on isn't the next index, set the after.
if (_currentSortIndex != _tierId + 1)
_tierIdAfter[msg.sender][_tierId] = _currentSortIndex;
// If this is the last tier being added, track the current last sort index if it's not already tracked.
if (
_i == _numberOfNewTiers - 1 &&
_trackedLastSortTierIdOf[msg.sender] != _currentLastSortIndex
) _trackedLastSortTierIdOf[msg.sender] = _currentLastSortIndex;
// If the previous after index was set to something else, set the previous after.
if (_previous != _tierId - 1 || _tierIdAfter[msg.sender][_previous] != 0)
// Set the tier after the previous one being iterated on as the tier being added, or 0 if the index is incremented.
_tierIdAfter[msg.sender][_previous] = _previous == _tierId - 1 ? 0 : _tierId;
// For the next tier being added, start at this current index.
_startSortIndex = _currentSortIndex;
// The tier just added is the previous for the next tier being added.
_previous = _tierId;
// Set current to zero to break out of the loop.
_currentSortIndex = 0;
}
// If the tier being iterated on is the last tier, add the tier after it.
else if (_next == 0 || _next > _currentMaxTierIdOf) {
if (_tierId != _currentSortIndex + 1)
_tierIdAfter[msg.sender][_currentSortIndex] = _tierId;
// For the next tier being added, start at this current index.
_startSortIndex = _tierId;
// Break out.
_currentSortIndex = 0;
// If there's currently a last sort index tracked, override it.
if (_trackedLastSortTierIdOf[msg.sender] != 0)
_trackedLastSortTierIdOf[msg.sender] = 0;
}
// Move on to the next index.
else {
// Set the previous index to be the current index.
_previous = _currentSortIndex;
// Go to the next index.
_currentSortIndex = _next;
}
}
}
// Set the tier ID in the returned value.
tierIds[_i] = _tierId;
unchecked {
++_i;
}
}
maxTierIdOf[msg.sender] = _currentMaxTierIdOf + _numberOfNewTiers;
}
/**
@notice
Mint a token within the tier for the provided value.
@dev
Only a project owner can mint tokens.
@param _tierId The ID of the tier to mint within.
@param _count The number of reserved tokens to mint.
@return tokenIds The IDs of the tokens being minted as reserves.
*/
function recordMintReservesFor(uint256 _tierId, uint256 _count)
external
override
returns (uint256[] memory tokenIds)
{
// Get a reference to the tier.
JBStored721Tier storage _storedTier = _storedTierOf[msg.sender][_tierId];
// Get a reference to the number of reserved tokens mintable for the tier.
uint256 _numberOfReservedTokensOutstanding = _numberOfReservedTokensOutstandingFor(
msg.sender,
_tierId,
_storedTier
);
// Can't mint more reserves than expected.
if (_count > _numberOfReservedTokensOutstanding) revert INSUFFICIENT_RESERVES();
// Increment the number of reserved tokens minted.
numberOfReservesMintedFor[msg.sender][_tierId] += _count;
// Initialize an array with the appropriate length.
tokenIds = new uint256[](_count);
// Keep a reference to the number of burned in the tier.
uint256 _numberOfBurnedFromTier = numberOfBurnedFor[msg.sender][_tierId];
for (uint256 _i; _i < _count; ) {
// Generate the tokens.
tokenIds[_i] = _generateTokenId(
_tierId,
_storedTier.initialQuantity - --_storedTier.remainingQuantity + _numberOfBurnedFromTier
);
unchecked {
++_i;
}
}
}
/**
@notice
Sets the reserved token beneficiary.
@param _beneficiary The reservd token beneficiary.
*/
function recordSetDefaultReservedTokenBeneficiary(address _beneficiary) external override {
defaultReservedTokenBeneficiaryOf[msg.sender] = _beneficiary;
}
/**
@notice
Record a token transfer.
@param _tierId The ID the tier being transfered
@param _from The sender of the token.
@param _to The recipient of the token.
*/
function recordTransferForTier(
uint256 _tierId,
address _from,
address _to
) external override {
// If this is not a mint then subtract the tier balance from the original holder.
if (_from != address(0))
// decrease the tier balance for the sender
--tierBalanceOf[msg.sender][_from][_tierId];
// if this is a burn the balance is not added
if (_to != address(0)) {
unchecked {
// increase the tier balance for the beneficiary
++tierBalanceOf[msg.sender][_to][_tierId];
}
}
}
/**
@notice
Remove tiers.
@param _tierIds The tiers IDs to remove.
*/
function recordRemoveTierIds(uint256[] calldata _tierIds) external override {
// Get a reference to the number of tiers being removed.
uint256 _numTiers = _tierIds.length;
// Keep a reference to the tier ID being iterated on.
uint256 _tierId;
for (uint256 _i; _i < _numTiers; ) {
// Set the tier being iterated on, 0-indexed
_tierId = _tierIds[_i];
// If the tier is locked throw an error.
if (_storedTierOf[msg.sender][_tierId].lockedUntil >= block.timestamp) revert TIER_LOCKED();
// Set the tier as removed.
_isTierRemoved[msg.sender].removeTier(_tierId);
unchecked {
++_i;
}
}
}
/**
@notice
Mints a token in the best available tier.
@param _amount The amount to base the mint on.
@return tokenId The token ID minted.
@return tierId The ID of the tier minted from.
@return leftoverAmount The amount leftover after the mint.
*/
function recordMintBestAvailableTier(uint256 _amount)
external
override
returns (
uint256 tokenId,
uint256 tierId,
uint256 leftoverAmount
)
{
// Keep a reference to the last tier ID.
uint256 _lastTierId = _lastSortIndexOf(msg.sender);
// Keep a reference to the tier being iterated on.
JBStored721Tier memory _storedTier;
// Keep a reference to the starting sort ID for sorting new tiers if needed.
// There's no need for sorting if there are currently no tiers.
// If there's no sort index, start with the first index.
uint256 _currentSortIndex = _firstSortIndexOf(msg.sender);
// Keep a reference to the best contribution floor.
uint256 _bestContributionFloor;
// Initialise a BitmapWord to read isRemoved
JBBitmapWord memory _bitmapWord = _isTierRemoved[msg.sender].readId(_currentSortIndex);
while (_currentSortIndex != 0) {
// Set the tier being iterated on. Tier's are 1 indexed.
_storedTier = _storedTierOf[msg.sender][_currentSortIndex];
// Is the current index outside the currently stored word?
if (_bitmapWord.refreshBitmapNeeded(_currentSortIndex))
_bitmapWord = _isTierRemoved[msg.sender].readId(_currentSortIndex);
// If the contribution floor has gone over, break out of the loop.
if (_storedTier.contributionFloor > _amount) _currentSortIndex = 0;
else {
// If the tier is not removed, check to see if it's optimal.
// Set the tier as the best available so far if there is still a remaining quantity.
if (
!_bitmapWord.isTierIdRemoved(_currentSortIndex) &&
_storedTier.contributionFloor > _bestContributionFloor &&
(_storedTier.remainingQuantity -
_numberOfReservedTokensOutstandingFor(msg.sender, _currentSortIndex, _storedTier)) !=
0
) {
tierId = _currentSortIndex;
_bestContributionFloor = _storedTier.contributionFloor;
}
// Set the next sort index.
_currentSortIndex = _nextSortIndex(msg.sender, _currentSortIndex, _lastTierId);
}
}
// If there's no best tier, return.
if (tierId == 0) leftoverAmount = _amount;
else {
// Keep a reference to the best tier.
JBStored721Tier storage _bestStoredTier = _storedTierOf[msg.sender][tierId];
// Make the token ID.
unchecked {
// Keep a reference to the token ID.
tokenId = _generateTokenId(
tierId,
_bestStoredTier.initialQuantity -
--_bestStoredTier.remainingQuantity +
numberOfBurnedFor[msg.sender][tierId]
);
}
// Set the leftover amount.
leftoverAmount = _amount - _bestContributionFloor;
}
}