-
Notifications
You must be signed in to change notification settings - Fork 20
/
MyLootBox.sol
387 lines (345 loc) · 12.1 KB
/
MyLootBox.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
pragma solidity ^0.5.11;
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./ERC1155Opensea.sol";
import "./MyFactory.sol";
import "./ILootBox.sol";
/**
* @title MyLootBox
* MyLootBox - a randomized and openable lootbox of ERC1155Opensea
*/
contract MyLootBox is ILootBox, Ownable, Pausable, ReentrancyGuard, MyFactory {
using SafeMath for uint256;
// Event for logging lootbox opens
event LootBoxOpened(uint256 indexed optionId, address indexed buyer, uint256 boxesPurchased, uint256 itemsMinted);
event Warning(string message, address account);
// Must be sorted by rarity
enum Class {
Common,
Rare,
Epic,
Legendary,
Divine,
Hidden
}
uint256 constant NUM_CLASSES = 6;
// NOTE: Price of the lootbox is set via sell orders on OpenSea
struct OptionSettings {
// Number of items to send per open.
// Set to 0 to disable this Option.
uint256 maxQuantityPerOpen;
// Probability in basis points (out of 10,000) of receiving each class (descending)
uint16[NUM_CLASSES] classProbabilities;
// Whether to enable `guarantees` below
bool hasGuaranteedClasses;
// Number of items you're guaranteed to get, for each class
uint16[NUM_CLASSES] guarantees;
}
mapping (uint256 => OptionSettings) public optionToSettings;
mapping (uint256 => uint256[]) public classToTokenIds;
mapping (uint256 => bool) public classIsPreminted;
uint256 seed;
uint256 constant INVERSE_BASIS_POINT = 10000;
/**
* @dev Example constructor. Calls setOptionSettings for you with
* sample settings
* @param _proxyRegistryAddress The address of the OpenSea/Wyvern proxy registry
* On Rinkeby: "0xf57b2c51ded3a29e6891aba85459d600256cf317"
* On mainnet: "0xa5409ec958c83c3f309868babaca7c86dcb077c1"
* @param _nftAddress The address of the non-fungible/semi-fungible item contract
* that you want to mint/transfer with each open
*/
constructor(
address _proxyRegistryAddress,
address _nftAddress
) MyFactory(
_proxyRegistryAddress,
_nftAddress
) public {
// Example settings and probabilities
// you can also call these after deploying
uint16[NUM_CLASSES] memory guarantees;
setOptionSettings(Option.Basic, 3, [7300, 2100, 400, 100, 50, 50], guarantees);
// Note that tokens ids will be one higher than the indexes used here.
guarantees[0] = 3;
setOptionSettings(Option.Premium, 5, [7200, 2100, 400, 200, 50, 50], guarantees);
guarantees[2] = 2;
guarantees[4] = 1;
setOptionSettings(Option.Gold, 7, [7000, 2100, 400, 400, 50, 50], guarantees);
}
//////
// INITIALIZATION FUNCTIONS FOR OWNER
//////
/**
* @dev If the tokens for some class are pre-minted and owned by the
* contract owner, they can be used for a given class by setting them here
*/
function setClassForTokenId(
uint256 _tokenId,
uint256 _classId
) public onlyOwner {
_checkTokenApproval();
_addTokenIdToClass(Class(_classId), _tokenId);
}
/**
* @dev Alternate way to add token ids to a class
* Note: resets the full list for the class instead of adding each token id
*/
function setTokenIdsForClass(
Class _class,
uint256[] memory _tokenIds
) public onlyOwner {
uint256 classId = uint256(_class);
classIsPreminted[classId] = true;
classToTokenIds[classId] = _tokenIds;
}
/**
* @dev Remove all token ids for a given class, causing it to fall back to
* creating/minting into the nft address
*/
function resetClass(
uint256 _classId
) public onlyOwner {
delete classIsPreminted[_classId];
delete classToTokenIds[_classId];
}
/**
* @dev Set token IDs for each rarity class. Bulk version of `setTokenIdForClass`
* @param _tokenIds List of token IDs to set for each class, specified above in order
*/
function setTokenIdsForClasses(
uint256[NUM_CLASSES] memory _tokenIds
) public onlyOwner {
_checkTokenApproval();
for (uint256 i = 0; i < _tokenIds.length; i++) {
Class class = Class(i);
_addTokenIdToClass(class, _tokenIds[i]);
}
}
/**
* @dev Set the settings for a particular lootbox option
* @param _option The Option to set settings for
* @param _maxQuantityPerOpen Maximum number of items to mint per open.
* Set to 0 to disable this option.
* @param _classProbabilities Array of probabilities (basis points, so integers out of 10,000)
* of receiving each class (the index in the array).
* Should add up to 10k and be descending in value.
* @param _guarantees Array of the number of guaranteed items received for each class
* (the index in the array).
*/
function setOptionSettings(
Option _option,
uint256 _maxQuantityPerOpen,
uint16[NUM_CLASSES] memory _classProbabilities,
uint16[NUM_CLASSES] memory _guarantees
) public onlyOwner {
// Allow us to skip guarantees and save gas at mint time
// if there are no classes with guarantees
bool hasGuaranteedClasses = false;
for (uint256 i = 0; i < _guarantees.length; i++) {
if (_guarantees[i] > 0) {
hasGuaranteedClasses = true;
}
}
OptionSettings memory settings = OptionSettings({
maxQuantityPerOpen: _maxQuantityPerOpen,
classProbabilities: _classProbabilities,
hasGuaranteedClasses: hasGuaranteedClasses,
guarantees: _guarantees
});
optionToSettings[uint256(_option)] = settings;
}
/**
* @dev Improve pseudorandom number generator by letting the owner set the seed manually,
* making attacks more difficult
* @param _newSeed The new seed to use for the next transaction
*/
function setSeed(uint256 _newSeed) public onlyOwner {
seed = _newSeed;
}
///////
// MAIN FUNCTIONS
//////
/**
* @dev Test mint function for The Contractor. Just for testing, replace eventually with a better reusable one.
* Creates 1 token of id 1, 2 tokens of id 2 and 3 tokens of id 3 for owner account
*/
function contractorTestMint(
address _toAddress
) external onlyOwner {
ERC1155Opensea nftContract = ERC1155Opensea(nftAddress);
nftContract.create(_toAddress, 1, "", "");
nftContract.create(_toAddress, 5, "", "");
nftContract.create(_toAddress, 10, "", "");
}
/**
* @dev Open a lootbox manually and send what's inside to _toAddress
* Convenience method for contract owner.
*/
function open(
uint256 _optionId,
address _toAddress,
uint256 _amount
) external onlyOwner {
_mint(Option(_optionId), _toAddress, _amount, "");
}
/**
* @dev Main minting logic for lootboxes
* This is called via safeTransferFrom when MyLootBox extends MyFactory.
* NOTE: prices and fees are determined by the sell order on OpenSea.
*/
function _mint(
Option _option,
address _toAddress,
uint256 _amount,
bytes memory /* _data */
) internal whenNotPaused nonReentrant {
// Load settings for this box option
uint256 optionId = uint256(_option);
OptionSettings memory settings = optionToSettings[optionId];
require(settings.maxQuantityPerOpen > 0, "MyLootBox#_mint: OPTION_NOT_ALLOWED");
require(_canMint(msg.sender, _option, _amount), "MyLootBox#_mint: CANNOT_MINT");
uint256 totalMinted = 0;
// Iterate over the quantity of boxes specified
for (uint256 i = 0; i < _amount; i++) {
// Iterate over the box's set quantity
uint256 quantitySent = 0;
if (settings.hasGuaranteedClasses) {
// Process guaranteed token ids
for (uint256 classId = 0; classId < settings.guarantees.length; classId++) {
if (classId > 0) {
uint256 quantityOfGaranteed = settings.guarantees[classId];
_sendTokenWithClass(Class(classId), _toAddress, quantityOfGaranteed);
quantitySent += quantityOfGaranteed;
}
}
}
// Process non-guaranteed ids
while (quantitySent < settings.maxQuantityPerOpen) {
uint256 quantityOfRandomized = 1;
Class class = _pickRandomClass(settings.classProbabilities);
_sendTokenWithClass(class, _toAddress, quantityOfRandomized);
quantitySent += quantityOfRandomized;
}
totalMinted += quantitySent;
}
// Event emissions
emit LootBoxOpened(optionId, _toAddress, _amount, totalMinted);
}
function withdraw() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
/////
// Metadata methods
/////
function name() external view returns (string memory) {
return "My Loot Box";
}
function symbol() external view returns (string memory) {
return "MYLOOT";
}
function uri(uint256 _optionId) external view returns (string memory) {
return Strings.strConcat(
baseMetadataURI,
"box/",
Strings.uint2str(_optionId)
);
}
/////
// HELPER FUNCTIONS
/////
// Returns the tokenId sent to _toAddress
function _sendTokenWithClass(
Class _class,
address _toAddress,
uint256 _amount
) internal returns (uint256) {
uint256 classId = uint256(_class);
ERC1155Opensea nftContract = ERC1155Opensea(nftAddress);
uint256 tokenId = _pickRandomAvailableTokenIdForClass(_class, _amount);
if (classIsPreminted[classId]) {
nftContract.safeTransferFrom(
owner(),
_toAddress,
tokenId,
_amount,
""
);
} else if (tokenId == 0) {
tokenId = nftContract.create(_toAddress, _amount, "", "");
classToTokenIds[classId].push(tokenId);
} else {
nftContract.mint(_toAddress, tokenId, _amount, "");
}
return tokenId;
}
function _pickRandomClass(
uint16[NUM_CLASSES] memory _classProbabilities
) internal returns (Class) {
uint16 value = uint16(_random().mod(INVERSE_BASIS_POINT));
// Start at top class (length - 1)
// skip common (0), we default to it
for (uint256 i = _classProbabilities.length - 1; i > 0; i--) {
uint16 probability = _classProbabilities[i];
if (value < probability) {
return Class(i);
} else {
value = value - probability;
}
}
return Class.Common;
}
function _pickRandomAvailableTokenIdForClass(
Class _class,
uint256 _minAmount
) internal returns (uint256) {
uint256 classId = uint256(_class);
uint256[] memory tokenIds = classToTokenIds[classId];
if (tokenIds.length == 0) {
// Unminted
require(
!classIsPreminted[classId],
"MyLootBox#_pickRandomAvailableTokenIdForClass: NO_TOKEN_ON_PREMINTED_CLASS"
);
return 0;
}
uint256 randIndex = _random().mod(tokenIds.length);
if (classIsPreminted[classId]) {
// Make sure owner() owns enough
ERC1155Opensea nftContract = ERC1155Opensea(nftAddress);
for (uint256 i = randIndex; i < randIndex + tokenIds.length; i++) {
uint256 tokenId = tokenIds[i % tokenIds.length];
if (nftContract.balanceOf(owner(), tokenId) >= _minAmount) {
return tokenId;
}
}
revert("MyLootBox#_pickRandomAvailableTokenIdForClass: NOT_ENOUGH_TOKENS_FOR_CLASS");
} else {
return tokenIds[randIndex];
}
}
/**
* @dev Pseudo-random number generator
* NOTE: to improve randomness, generate it with an oracle
*/
function _random() internal returns (uint256) {
uint256 randomNumber = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, seed)));
seed = randomNumber;
return randomNumber;
}
/**
* @dev emit a Warning if we're not approved to transfer nftAddress
*/
function _checkTokenApproval() internal {
ERC1155Opensea nftContract = ERC1155Opensea(nftAddress);
if (!nftContract.isApprovedForAll(owner(), address(this))) {
emit Warning("Lootbox contract is not approved for trading collectible by:", owner());
}
}
function _addTokenIdToClass(Class _class, uint256 _tokenId) internal {
uint256 classId = uint256(_class);
classIsPreminted[classId] = true;
classToTokenIds[classId].push(_tokenId);
}
}