-
Notifications
You must be signed in to change notification settings - Fork 2
/
contract.sol
2768 lines (2395 loc) · 96.9 KB
/
contract.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
///////////////////////////////////////////
// File: /app/contracts/Indelible.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "erc721a/contracts/ERC721A.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./SSTORE2.sol";
import "./DynamicBuffer.sol";
import "./HelperLib.sol";
contract Indelible is ERC721A, ReentrancyGuard, Ownable {
using HelperLib for uint;
using DynamicBuffer for bytes;
struct LinkedTraitDTO {
uint[] traitA;
uint[] traitB;
}
struct TraitDTO {
string name;
string mimetype;
bytes data;
bool useExistingData;
uint existingDataIndex;
}
struct Trait {
string name;
string mimetype;
}
struct ContractData {
string name;
string description;
string image;
string banner;
string website;
uint royalties;
string royaltiesRecipient;
}
struct WithdrawRecipient {
string name;
string imageUrl;
address recipientAddress;
uint percentage;
}
mapping(uint => address[]) internal _traitDataPointers;
mapping(uint => mapping(uint => Trait)) internal _traitDetails;
mapping(uint => bool) internal _renderTokenOffChain;
mapping(uint => mapping(uint => uint[])) internal _linkedTraits;
uint private constant DEVELOPER_FEE = 250; // of 10,000 = 2.5%
uint private constant NUM_LAYERS = 9;
uint private constant MAX_BATCH_MINT = 20;
uint[][NUM_LAYERS] private TIERS;
string[] private LAYER_NAMES = [unicode"Jewelry", unicode"Beauty Marks", unicode"Eyes", unicode"Pretty Mouths", unicode"Necks", unicode"Hair Hats and Wigs", unicode"Punkins", unicode"Zodiak", unicode"Spooky Sky"];
bool private shouldWrapSVG = true;
string private backgroundColor = "transparent";
WithdrawRecipient[1] public withdrawRecipients;
bool public isContractSealed;
uint public constant maxSupply = 6969;
uint public maxPerAddress = 20;
uint public publicMintPrice = 0.006969 ether;
string public baseURI = "";
bool public isPublicMintActive;
bytes32 private merkleRoot;
uint public allowListPrice = 0.000 ether;
uint public maxPerAllowList = 3;
bool public isAllowListActive;
ContractData public contractData = ContractData(unicode"Punkin Spicies", unicode"6969 Little Punk Cuties Derivative Spicy and On Chain", "https://indeliblelabs-prod.s3.us-east-2.amazonaws.com/profile/196f7277-390d-45ff-a605-9c8de357782e", "https://indeliblelabs-prod.s3.us-east-2.amazonaws.com/banner/196f7277-390d-45ff-a605-9c8de357782e", "", 500, "0xf2c0149F0cff4c19b9819d1084f465DF0E1b3795");
constructor() ERC721A(unicode"Punkin Spicies", unicode"PunkinSpicies") {
TIERS[0] = [64,206,1744,1752,3203];
TIERS[1] = [109,321,349,1561,1879,2750];
TIERS[2] = [53,74,87,100,131,136,144,195,199,208,233,327,440,441,500,518,609,711,749,1114];
TIERS[3] = [29,65,216,315,592,786,898,1200,1302,1566];
TIERS[4] = [494,1027,1102,1689,2657];
TIERS[5] = [9,18,19,29,41,42,51,70,87,89,91,92,104,124,135,144,150,151,172,182,182,193,194,197,201,217,218,235,235,255,261,291,312,384,409,553,832];
TIERS[6] = [40,80,81,149,185,198,257,342,383,435,674,679,869,1237,1360];
TIERS[7] = [107,107,160,204,212,545,616,630,803,808,1121,1656];
TIERS[8] = [6969];
withdrawRecipients[0] = WithdrawRecipient(unicode"null",unicode"null", 0x5FD2E3ba05C862E62a34B9F63c45C0DF622Ac112, 5000);
}
modifier whenMintActive() {
require(isMintActive(), "Minting is not active");
_;
}
modifier whenUnsealed() {
require(!isContractSealed, "Contract is sealed");
_;
}
receive() external payable {
require(isPublicMintActive, "Public minting is not active");
handleMint(msg.value / publicMintPrice);
}
function rarityGen(uint _randinput, uint _rarityTier)
internal
view
returns (uint)
{
uint currentLowerBound = 0;
for (uint i = 0; i < TIERS[_rarityTier].length; i++) {
uint thisPercentage = TIERS[_rarityTier][i];
if (
_randinput >= currentLowerBound &&
_randinput < currentLowerBound + thisPercentage
) return i;
currentLowerBound = currentLowerBound + thisPercentage;
}
revert();
}
function entropyForExtraData() internal view returns (uint24) {
uint randomNumber = uint(
keccak256(
abi.encodePacked(
tx.gasprice,
block.number,
block.timestamp,
block.difficulty,
blockhash(block.number - 1),
msg.sender
)
)
);
return uint24(randomNumber);
}
function stringCompare(string memory a, string memory b) internal pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
function tokensAreDuplicates(uint tokenIdA, uint tokenIdB) public view returns (bool) {
return stringCompare(
tokenIdToHash(tokenIdA),
tokenIdToHash(tokenIdB)
);
}
function reRollDuplicate(
uint tokenIdA,
uint tokenIdB
) public whenUnsealed {
require(tokensAreDuplicates(tokenIdA, tokenIdB), "All tokens must be duplicates");
uint largerTokenId = tokenIdA > tokenIdB ? tokenIdA : tokenIdB;
if (msg.sender != owner()) {
require(msg.sender == ownerOf(largerTokenId), "Only the token owner or contract owner can re-roll");
}
_initializeOwnershipAt(largerTokenId);
if (_exists(largerTokenId + 1)) {
_initializeOwnershipAt(largerTokenId + 1);
}
_setExtraDataAt(largerTokenId, entropyForExtraData());
}
function _extraData(
address from,
address to,
uint24 previousExtraData
) internal view virtual override returns (uint24) {
return from == address(0) ? entropyForExtraData() : previousExtraData;
}
function getTokenSeed(uint _tokenId) internal view returns (uint24) {
return _ownershipOf(_tokenId).extraData;
}
function tokenIdToHash(
uint _tokenId
) public view returns (string memory) {
require(_exists(_tokenId), "Invalid token");
// This will generate a NUM_LAYERS * 3 character string.
bytes memory hashBytes = DynamicBuffer.allocate(NUM_LAYERS * 4);
uint[] memory hash = new uint[](NUM_LAYERS);
bool[] memory modifiedLayers = new bool[](NUM_LAYERS);
for (uint i = 0; i < NUM_LAYERS; i++) {
uint traitIndex = hash[i];
if (modifiedLayers[i] == false) {
uint _randinput = uint(
uint(
keccak256(
abi.encodePacked(
getTokenSeed(_tokenId),
_tokenId,
_tokenId + i
)
)
) % maxSupply
);
traitIndex = rarityGen(_randinput, i);
hash[i] = traitIndex;
}
if (_linkedTraits[i][traitIndex].length > 0) {
hash[_linkedTraits[i][traitIndex][0]] = _linkedTraits[i][traitIndex][1];
modifiedLayers[_linkedTraits[i][traitIndex][0]] = true;
}
}
for (uint i = 0; i < hash.length; i++) {
if (hash[i] < 10) {
hashBytes.appendSafe("00");
} else if (hash[i] < 100) {
hashBytes.appendSafe("0");
}
if (hash[i] > 999) {
hashBytes.appendSafe("999");
} else {
hashBytes.appendSafe(bytes(_toString(hash[i])));
}
}
return string(hashBytes);
}
function handleMint(uint256 _count) internal whenMintActive returns (uint256) {
uint256 totalMinted = _totalMinted();
require(_count > 0, "Invalid token count");
require(totalMinted + _count <= maxSupply, "All tokens are gone");
if (isPublicMintActive) {
if (msg.sender != owner()) {
require(_numberMinted(msg.sender) + _count <= maxPerAddress, "Exceeded max mints allowed");
}
require(msg.sender == tx.origin, "EOAs only");
require(_count * publicMintPrice == msg.value, "Incorrect amount of ether sent");
}
uint256 batchCount = _count / MAX_BATCH_MINT;
uint256 remainder = _count % MAX_BATCH_MINT;
for (uint256 i = 0; i < batchCount; i++) {
_mint(msg.sender, MAX_BATCH_MINT);
}
if (remainder > 0) {
_mint(msg.sender, remainder);
}
return totalMinted;
}
function mint(uint256 _count, bytes32[] calldata merkleProof)
external
payable
nonReentrant
whenMintActive
returns (uint)
{
if (!isPublicMintActive) {
if (msg.sender != owner()) {
require(onAllowList(msg.sender, merkleProof), "Not on allow list");
require(_numberMinted(msg.sender) + _count <= maxPerAllowList, "Exceeded max mints allowed");
}
require(_count * allowListPrice == msg.value, "Incorrect amount of ether sent");
}
uint256 totalMinted = handleMint(_count);
return totalMinted;
}
function isMintActive() public view returns (bool) {
return _totalMinted() < maxSupply && (isPublicMintActive || isAllowListActive);
}
function hashToSVG(string memory _hash)
public
view
returns (string memory)
{
uint thisTraitIndex;
bytes memory svgBytes = DynamicBuffer.allocate(1024 * 128);
svgBytes.appendSafe('<svg width="1200" height="1200" viewBox="0 0 1200 1200" version="1.2" xmlns="http://www.w3.org/2000/svg" style="background-color:');
svgBytes.appendSafe(
abi.encodePacked(
backgroundColor,
";background-image:url("
)
);
for (uint i = 0; i < NUM_LAYERS - 1; i++) {
thisTraitIndex = HelperLib.parseInt(
HelperLib._substring(_hash, (i * 3), (i * 3) + 3)
);
svgBytes.appendSafe(
abi.encodePacked(
"data:",
_traitDetails[i][thisTraitIndex].mimetype,
";base64,",
Base64.encode(SSTORE2.read(_traitDataPointers[i][thisTraitIndex])),
"),url("
)
);
}
thisTraitIndex = HelperLib.parseInt(
HelperLib._substring(_hash, (NUM_LAYERS * 3) - 3, NUM_LAYERS * 3)
);
svgBytes.appendSafe(
abi.encodePacked(
"data:",
_traitDetails[NUM_LAYERS - 1][thisTraitIndex].mimetype,
";base64,",
Base64.encode(SSTORE2.read(_traitDataPointers[NUM_LAYERS - 1][thisTraitIndex])),
');background-repeat:no-repeat;background-size:contain;background-position:center;image-rendering:-webkit-optimize-contrast;-ms-interpolation-mode:nearest-neighbor;image-rendering:-moz-crisp-edges;image-rendering:pixelated;"></svg>'
)
);
return string(
abi.encodePacked(
"data:image/svg+xml;base64,",
Base64.encode(svgBytes)
)
);
}
function hashToMetadata(string memory _hash)
public
view
returns (string memory)
{
bytes memory metadataBytes = DynamicBuffer.allocate(1024 * 128);
metadataBytes.appendSafe("[");
for (uint i = 0; i < NUM_LAYERS; i++) {
uint thisTraitIndex = HelperLib.parseInt(
HelperLib._substring(_hash, (i * 3), (i * 3) + 3)
);
metadataBytes.appendSafe(
abi.encodePacked(
'{"trait_type":"',
LAYER_NAMES[i],
'","value":"',
_traitDetails[i][thisTraitIndex].name,
'"}'
)
);
if (i == NUM_LAYERS - 1) {
metadataBytes.appendSafe("]");
} else {
metadataBytes.appendSafe(",");
}
}
return string(metadataBytes);
}
function onAllowList(address addr, bytes32[] calldata merkleProof) public view returns (bool) {
return MerkleProof.verify(merkleProof, merkleRoot, keccak256(abi.encodePacked(addr)));
}
function tokenURI(uint _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId), "Invalid token");
require(_traitDataPointers[0].length > 0, "Traits have not been added");
string memory tokenHash = tokenIdToHash(_tokenId);
bytes memory jsonBytes = DynamicBuffer.allocate(1024 * 128);
jsonBytes.appendSafe(unicode"{\"name\":\"Punkin Spicies #");
jsonBytes.appendSafe(
abi.encodePacked(
_toString(_tokenId),
"\",\"description\":\"",
contractData.description,
"\","
)
);
if (bytes(baseURI).length > 0 && _renderTokenOffChain[_tokenId]) {
jsonBytes.appendSafe(
abi.encodePacked(
'"image":"',
baseURI,
_toString(_tokenId),
"?dna=",
tokenHash,
'&network=mainnet",'
)
);
} else {
string memory svgCode = "";
if (shouldWrapSVG) {
string memory svgString = hashToSVG(tokenHash);
svgCode = string(
abi.encodePacked(
"data:image/svg+xml;base64,",
Base64.encode(
abi.encodePacked(
'<svg width="100%" height="100%" viewBox="0 0 1200 1200" version="1.2" xmlns="http://www.w3.org/2000/svg"><image width="1200" height="1200" href="',
svgString,
'"></image></svg>'
)
)
)
);
jsonBytes.appendSafe(
abi.encodePacked(
'"svg_image_data":"',
svgString,
'",'
)
);
} else {
svgCode = hashToSVG(tokenHash);
}
jsonBytes.appendSafe(
abi.encodePacked(
'"image_data":"',
svgCode,
'",'
)
);
}
jsonBytes.appendSafe(
abi.encodePacked(
'"attributes":',
hashToMetadata(tokenHash),
"}"
)
);
return string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(jsonBytes)
)
);
}
function contractURI()
public
view
returns (string memory)
{
return string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
abi.encodePacked(
'{"name":"',
contractData.name,
'","description":"',
contractData.description,
'","image":"',
contractData.image,
'","banner":"',
contractData.banner,
'","external_link":"',
contractData.website,
'","seller_fee_basis_points":',
_toString(contractData.royalties),
',"fee_recipient":"',
contractData.royaltiesRecipient,
'"}'
)
)
)
);
}
function tokenIdToSVG(uint _tokenId)
public
view
returns (string memory)
{
return hashToSVG(tokenIdToHash(_tokenId));
}
function traitDetails(uint _layerIndex, uint _traitIndex)
public
view
returns (Trait memory)
{
return _traitDetails[_layerIndex][_traitIndex];
}
function traitData(uint _layerIndex, uint _traitIndex)
public
view
returns (string memory)
{
return string(SSTORE2.read(_traitDataPointers[_layerIndex][_traitIndex]));
}
function getLinkedTraits(uint _layerIndex, uint _traitIndex)
public
view
returns (uint[] memory)
{
return _linkedTraits[_layerIndex][_traitIndex];
}
function addLayer(uint _layerIndex, TraitDTO[] memory traits)
public
onlyOwner
whenUnsealed
{
require(TIERS[_layerIndex].length == traits.length, "Traits size does not match tiers for this index");
address[] memory dataPointers = new address[](traits.length);
for (uint i = 0; i < traits.length; i++) {
if (traits[i].useExistingData) {
dataPointers[i] = dataPointers[traits[i].existingDataIndex];
} else {
dataPointers[i] = SSTORE2.write(traits[i].data);
}
_traitDetails[_layerIndex][i] = Trait(traits[i].name, traits[i].mimetype);
}
_traitDataPointers[_layerIndex] = dataPointers;
return;
}
function addTrait(uint _layerIndex, uint _traitIndex, TraitDTO memory trait)
public
onlyOwner
whenUnsealed
{
_traitDetails[_layerIndex][_traitIndex] = Trait(trait.name, trait.mimetype);
address[] memory dataPointers = _traitDataPointers[_layerIndex];
if (trait.useExistingData) {
dataPointers[_traitIndex] = dataPointers[trait.existingDataIndex];
} else {
dataPointers[_traitIndex] = SSTORE2.write(trait.data);
}
_traitDataPointers[_layerIndex] = dataPointers;
return;
}
function setLinkedTraits(LinkedTraitDTO[] memory linkedTraits)
public
onlyOwner
whenUnsealed
{
for (uint i = 0; i < linkedTraits.length; i++) {
_linkedTraits[linkedTraits[i].traitA[0]][linkedTraits[i].traitA[1]] = [linkedTraits[i].traitB[0],linkedTraits[i].traitB[1]];
}
}
function setContractData(ContractData memory _contractData) external onlyOwner whenUnsealed {
contractData = _contractData;
}
function setMaxPerAddress(uint _maxPerAddress) external onlyOwner {
maxPerAddress = _maxPerAddress;
}
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
function setBackgroundColor(string memory _backgroundColor) external onlyOwner whenUnsealed {
backgroundColor = _backgroundColor;
}
function setRenderOfTokenId(uint _tokenId, bool _renderOffChain) external {
require(msg.sender == ownerOf(_tokenId), "Only the token owner can set the render method");
_renderTokenOffChain[_tokenId] = _renderOffChain;
}
function setMerkleRoot(bytes32 newMerkleRoot) external onlyOwner {
merkleRoot = newMerkleRoot;
}
function setMaxPerAllowList(uint _maxPerAllowList) external onlyOwner {
maxPerAllowList = _maxPerAllowList;
}
function setAllowListPrice(uint _allowListPrice) external onlyOwner {
allowListPrice = _allowListPrice;
}
function toggleAllowListMint() external onlyOwner {
isAllowListActive = !isAllowListActive;
}
function toggleWrapSVG() external onlyOwner {
shouldWrapSVG = !shouldWrapSVG;
}
function togglePublicMint() external onlyOwner {
isPublicMintActive = !isPublicMintActive;
}
function sealContract() external whenUnsealed onlyOwner {
isContractSealed = true;
}
function withdraw() external onlyOwner nonReentrant {
uint balance = address(this).balance;
uint amount = (balance * (10000 - DEVELOPER_FEE)) / 10000;
uint distAmount = 0;
uint totalDistributionPercentage = 0;
address payable receiver = payable(owner());
address payable dev = payable(0xEA208Da933C43857683C04BC76e3FD331D7bfdf7);
Address.sendValue(dev, balance - amount);
if (withdrawRecipients.length > 0) {
for (uint i = 0; i < withdrawRecipients.length; i++) {
totalDistributionPercentage = totalDistributionPercentage + withdrawRecipients[i].percentage;
address payable currRecepient = payable(withdrawRecipients[i].recipientAddress);
distAmount = (amount * (10000 - withdrawRecipients[i].percentage)) / 10000;
Address.sendValue(currRecepient, amount - distAmount);
}
}
balance = address(this).balance;
Address.sendValue(receiver, balance);
}
}
///////////////////////////////////////////
// File: /app/contracts/DynamicBuffer.sol
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
pragma solidity >=0.8.0;
/// @title DynamicBuffer
/// @author David Huber (@cxkoda) and Simon Fremaux (@dievardump). See also
/// https://raw.githubusercontent.com/dievardump/solidity-dynamic-buffer
/// @notice This library is used to allocate a big amount of container memory
// which will be subsequently filled without needing to reallocate
/// memory.
/// @dev First, allocate memory.
/// Then use `buffer.appendUnchecked(theBytes)` or `appendSafe()` if
/// bounds checking is required.
library DynamicBuffer {
/// @notice Allocates container space for the DynamicBuffer
/// @param capacity The intended max amount of bytes in the buffer
/// @return buffer The memory location of the buffer
/// @dev Allocates `capacity + 0x60` bytes of space
/// The buffer array starts at the first container data position,
/// (i.e. `buffer = container + 0x20`)
function allocate(uint256 capacity)
internal
pure
returns (bytes memory buffer)
{
assembly {
// Get next-free memory address
let container := mload(0x40)
// Allocate memory by setting a new next-free address
{
// Add 2 x 32 bytes in size for the two length fields
// Add 32 bytes safety space for 32B chunked copy
let size := add(capacity, 0x60)
let newNextFree := add(container, size)
mstore(0x40, newNextFree)
}
// Set the correct container length
{
let length := add(capacity, 0x40)
mstore(container, length)
}
// The buffer starts at idx 1 in the container (0 is length)
buffer := add(container, 0x20)
// Init content with length 0
mstore(buffer, 0)
}
return buffer;
}
/// @notice Appends data to buffer, and update buffer length
/// @param buffer the buffer to append the data to
/// @param data the data to append
/// @dev Does not perform out-of-bound checks (container capacity)
/// for efficiency.
function appendUnchecked(bytes memory buffer, bytes memory data)
internal
pure
{
assembly {
let length := mload(data)
for {
data := add(data, 0x20)
let dataEnd := add(data, length)
let copyTo := add(buffer, add(mload(buffer), 0x20))
} lt(data, dataEnd) {
data := add(data, 0x20)
copyTo := add(copyTo, 0x20)
} {
// Copy 32B chunks from data to buffer.
// This may read over data array boundaries and copy invalid
// bytes, which doesn't matter in the end since we will
// later set the correct buffer length, and have allocated an
// additional word to avoid buffer overflow.
mstore(copyTo, mload(data))
}
// Update buffer length
mstore(buffer, add(mload(buffer), length))
}
}
/// @notice Appends data to buffer, and update buffer length
/// @param buffer the buffer to append the data to
/// @param data the data to append
/// @dev Performs out-of-bound checks and calls `appendUnchecked`.
function appendSafe(bytes memory buffer, bytes memory data) internal pure {
uint256 capacity;
uint256 length;
assembly {
capacity := sub(mload(sub(buffer, 0x20)), 0x40)
length := mload(buffer)
}
require(
length + data.length <= capacity,
"DynamicBuffer: Appending out of bounds."
);
appendUnchecked(buffer, data);
}
}
///////////////////////////////////////////
// File: /app/contracts/HelperLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
library HelperLib {
function parseInt(string memory _a)
internal
pure
returns (uint8 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
function _substring(
string memory str,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
}
///////////////////////////////////////////
// File: /app/contracts/SSTORE2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./utils/Bytecode.sol";
/**
@title A key-value storage with auto-generated keys for storing chunks of data with a lower write & read cost.
@author Agustin Aguilar <[email protected]>
Readme: https://github.com/0xsequence/sstore2#readme
*/
library SSTORE2 {
error WriteError();
/**
@notice Stores `_data` and returns `pointer` as key for later retrieval
@dev The pointer is a contract address with `_data` as code
@param _data to be written
@return pointer Pointer to the written `_data`
*/
function write(bytes memory _data) internal returns (address pointer) {
// Append 00 to _data so contract can't be called
// Build init code
bytes memory code = Bytecode.creationCodeFor(
abi.encodePacked(
hex'00',
_data
)
);
// Deploy contract using create
assembly { pointer := create(0, add(code, 32), mload(code)) }
// Address MUST be non-zero
if (pointer == address(0)) revert WriteError();
}
/**
@notice Reads the contents of the `_pointer` code as data, skips the first byte
@dev The function is intended for reading pointers generated by `write`
@param _pointer to be read
@return data read from `_pointer` contract
*/
function read(address _pointer) internal view returns (bytes memory) {
return Bytecode.codeAt(_pointer, 1, type(uint256).max);
}
/**
@notice Reads the contents of the `_pointer` code as data, skips the first byte
@dev The function is intended for reading pointers generated by `write`
@param _pointer to be read
@param _start number of bytes to skip
@return data read from `_pointer` contract
*/
function read(address _pointer, uint256 _start) internal view returns (bytes memory) {
return Bytecode.codeAt(_pointer, _start + 1, type(uint256).max);
}
/**
@notice Reads the contents of the `_pointer` code as data, skips the first byte
@dev The function is intended for reading pointers generated by `write`
@param _pointer to be read
@param _start number of bytes to skip
@param _end index before which to end extraction
@return data read from `_pointer` contract
*/
function read(address _pointer, uint256 _start, uint256 _end) internal view returns (bytes memory) {
return Bytecode.codeAt(_pointer, _start + 1, _end + 1);
}
}
///////////////////////////////////////////
// File: /app/contracts/utils/Bytecode.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Bytecode {
error InvalidCodeAtRange(uint256 _size, uint256 _start, uint256 _end);
/**
@notice Generate a creation code that results on a contract with `_code` as bytecode
@param _code The returning value of the resulting `creationCode`
@return creationCode (constructor) for new contract
*/
function creationCodeFor(bytes memory _code) internal pure returns (bytes memory) {
/*
0x00 0x63 0x63XXXXXX PUSH4 _code.length size
0x01 0x80 0x80 DUP1 size size
0x02 0x60 0x600e PUSH1 14 14 size size
0x03 0x60 0x6000 PUSH1 00 0 14 size size
0x04 0x39 0x39 CODECOPY size
0x05 0x60 0x6000 PUSH1 00 0 size
0x06 0xf3 0xf3 RETURN
<CODE>
*/
return abi.encodePacked(
hex"63",
uint32(_code.length),
hex"80_60_0E_60_00_39_60_00_F3",
_code
);
}
/**
@notice Returns the size of the code on a given address
@param _addr Address that may or may not contain code
@return size of the code on the given `_addr`
*/
function codeSize(address _addr) internal view returns (uint256 size) {
assembly { size := extcodesize(_addr) }
}
/**
@notice Returns the code of a given address
@dev It will fail if `_end < _start`
@param _addr Address that may or may not contain code
@param _start number of bytes of code to skip on read
@param _end index before which to end extraction
@return oCode read from `_addr` deployed bytecode
Forked from: https://gist.github.com/KardanovIR/fe98661df9338c842b4a30306d507fbd
*/
function codeAt(address _addr, uint256 _start, uint256 _end) internal view returns (bytes memory oCode) {
uint256 csize = codeSize(_addr);
if (csize == 0) return bytes("");
if (_start > csize) return bytes("");
if (_end < _start) revert InvalidCodeAtRange(csize, _start, _end);
unchecked {
uint256 reqSize = _end - _start;
uint256 maxSize = csize - _start;
uint256 size = maxSize < reqSize ? maxSize : reqSize;
assembly {
// allocate output byte array - this could also be done without assembly
// by using o_code = new bytes(size)
oCode := mload(0x40)
// new "memory end" including padding
mstore(0x40, add(oCode, and(add(add(size, 0x20), 0x1f), not(0x1f))))
// store length in memory
mstore(oCode, size)
// actually retrieve the code, this needs assembly
extcodecopy(_addr, add(oCode, 0x20), _start, size)
}
}
}
}
///////////////////////////////////////////
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}